<?php
/**
 * ShopEx licence edit by kim
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_ctl_site_member extends b2c_frontpage{

    function __construct(&$app){
        parent::__construct($app);

        $this->header .= '<meta name="robots" content="noindex,noarchive,nofollow" />';
        $this->_response->set_header('Cache-Control', 'no-store');

        $this->verify_member();
        $this->pagesize = 10;
        $this->action = $this->_request->get_act_name();
        if(!$this->action) $this->action = 'index';
        $this->action_view = $this->action.".html";
        $this->member = $this->get_current_member();

        $this->load_info();

        //根据不同的角色显示不同的内容
        $shopname = app::get('site')->getConf('site.name');
        if($this->pagedata['is_personal']==0){
            if(isset($shopname)){
                $this->title = app::get('b2c')->_('我是买家_会员中心').'_'.$shopname;
                $this->keywords = app::get('b2c')->_('我是买家_会员中心').'_'.$shopname;
                $this->description = app::get('b2c')->_('我是买家_会员中心').'_'.$shopname;
            }
        }elseif($this->pagedata['is_personal']==1){
            if(isset($shopname)){
                $this->title = app::get('b2c')->_('我是卖家').'_'.$shopname;
                $this->keywords = app::get('b2c')->_('我是卖家').'_'.$shopname;
                $this->description = app::get('b2c')->_('我是买家').'_'.$shopname;
            }
        }else{
            if(isset($shopname)){
                $this->title = app::get('b2c')->_('集货员').'_'.$shopname;
                $this->keywords = app::get('b2c')->_('集货员').'_'.$shopname;
                $this->description = app::get('b2c')->_('集货员').'_'.$shopname;
            }
        }

        //个人用户不能对供应商的内容进行操作
        $this->is_personal=$this->pagedata['is_personal'];
        if($this->pagedata['is_personal']!=1 && $_SERVER["HTTP_X_REQUESTED_WITH"]!="XMLHttpRequest" ){
            $class=$this->_request->get_act_name();
            if(in_array($class, array('businessbaseinfo','preserve_product','none_product','goods_edit'))){
                $this->splash('failed', $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index')), app::get('b2c')->_('个人用户，不能进行该项操作'),false);
            }
        }
        /** end **/
    }

    /*
     *会员中心左侧菜单栏 edit by kim
     * */
    private function get_cpmenu(){
        //子账号不显示供应商信息维护
        if($this->pagedata["role_business"]==1){
            //-----liuyulie供应商不能修改自己的信息-----
            //$barr = array('label' => app::get('b2c')->_('供应商信息维护'), 'app' => 'b2c', 'ctl' => 'site_member', 'link' => 'businessbaseinfo');
        }else{
            $barr = array();
        }
        // 判断是否开启预存款
        $mdl_payment_cfgs = app::get('ectools')->model('payment_cfgs');
        $payment_info = $mdl_payment_cfgs->getPaymentInfo('deposit');
        $arr_blance = array();
        $arr_recharge_blance = array();
        $arr_point_history = array();
        $arr_point_coupon_exchange = array();
        $this->pagedata['point_usaged'] = "false";

        if ($payment_info['app_staus'] == app::get('ectools')->_('开启'))
        {
            $this->pagedata['deposit_status'] = 'true';
            $arr_blance = array('label'=>app::get('b2c')->_('我的预存款'),'app'=>'b2c','ctl'=>'site_member','link'=>'balance');
//            $arr_recharge_blance = array('label'=>app::get('b2c')->_('预存款充值'),'app'=>'b2c','ctl'=>'site_member','link'=>'deposit');
        }

        $site_get_policy_method = $this->app->getConf('site.get_policy.method');
        if ($site_get_policy_method != '1')
        {
            $arr_point_history = array('label'=>app::get('b2c')->_('积分历史'),'app'=>'b2c','ctl'=>'site_member','link'=>'point_history');
            $arr_point_coupon_exchange = array('label'=>app::get('b2c')->_('积分兑换优惠券'),'app'=>'b2c','ctl'=>'site_member','link'=>'couponExchange');
            $this->pagedata['point_usaged'] = "true";
        }

        $this->pagedata['comment_switch_discuss'] = $this->app->getConf('comment.switch.discuss');
        $this->pagedata['comment_switch_ask'] = $this->app->getConf('comment.switch.ask');

        if($this->pagedata['comment_switch_discuss'] == 'on'){
            //未评论商品
            $nodiscuss = array('label'=>app::get('b2c')->_('未评论商品'),'app'=>'b2c','ctl'=>'site_member','link'=>'nodiscuss');
            $comment_tab = array('label'=>app::get('b2c')->_('我的评论'),'app'=>'b2c','ctl'=>'site_member','link'=>'comment');
        }
        if($this->pagedata['comment_switch_discuss'] == 'on' && $this->pagedata['comment_switch_ask'] == 'on'){
            $comment_tab = array('label'=>app::get('b2c')->_('评论与咨询'),'app'=>'b2c','ctl'=>'site_member','link'=>'comment');
        }elseif($this->pagedata['comment_switch_ask'] == 'on'){
            $comment_tab = array('label'=>app::get('b2c')->_('我的咨询'),'app'=>'b2c','ctl'=>'site_member','link'=>'ask');
        }

        if($this->pagedata['comment_switch_ask'] == 'on' || $this->pagedata['comment_switch_discuss'] == 'on'){
            $comment['label'] = app::get('b2c')->_('评论咨询管理');
            $comment['mid'] = 2;
            if($nodiscuss){
                $comment['items'][] = $nodiscuss;
            }
            $comment['items'][] = $comment_tab;
        }
        //默认显示user_type:1 供应商内容，集货员的还未添加 edit by kim
        if($this->pagedata['is_personal']== 1){
            $arr_bases = array(
                //供应商管理不同于会员的内容
                array(
                    'label'=>app::get('b2c')->_('商品管理 Управление товаром'),
                    'mid'=>0,
                    'items'=>array(
                        array('label' => app::get('b2c')->_('在售商品 Товары в продаже'), 'app' => 'b2c', 'ctl' => 'site_member', 'link' => 'preserve_product'),
                        array('label' => app::get('b2c')->_('下架商品 Товары не в продаже'), 'app'=>'b2c', 'ctl'=>'site_member', 'link'=>'none_product'),
                        array('label'=>app::get('b2c')->_('新订单 новый заказ'),'app'=>'b2c','ctl'=>'site_member','link'=>'no_inventory'),
                        array('label'=>app::get('b2c')->_('已确认订单 Подтвержден заказ'),'app'=>'b2c','ctl'=>'site_member','link'=>'confirmed'),
                        //$barr,
                    )
                ),
            );
        }
        //集货员--by yyj 2015/10/9
        if($this->pagedata['is_personal']== 2){
            $arr_bases = array(
                //集货单管理不同于会员的内容
                array(
                    'label'=>app::get('b2c')->_('集货单管理'),
                    'mid'=>0,
                    'items'=>array(
                        array('label' => app::get('b2c')->_('我的集货单'), 'app' => 'b2c', 'ctl' => 'site_member', 'link' => 'collect_order'),

                    )
                ),
            );
        }
        //当user_type:0时，显示普通会员的内容
        if($this->pagedata['is_personal']== 0){
            $arr_bases = array(
                array(
                    'label'=>app::get('b2c')->_('交易管理'),
                    'mid'=>0,
                    'items'=>array(
                        array('label'=>app::get('b2c')->_('我的订单'),'app'=>'b2c','ctl'=>'site_member','link'=>'orders'),
                    )
                ),
                //我的最爱
                array(
                    'label'=>app::get('b2c')->_('我的最爱'),
                    'mid'=>5,
                    'items'=>array(
                        array('label'=>app::get('b2c')->_('我的购物车'),'app'=>'b2c','ctl'=>'site_cart','link'=>'index'),
                        array('label'=>app::get('b2c')->_('我的收藏'),'app'=>'b2c','ctl'=>'site_member','link'=>'favorite'),
                    )
                ),
                //评论咨询
                $comment,
                array(
                    'label'=>app::get('b2c')->_('我的账户'),
                    'mid'=>1,
                    'items'=>array(
//                        array('label'=>app::get('b2c')->_('商品收藏'),'app'=>'b2c','ctl'=>'site_member','link'=>'favorite'),
                        array('label'=>app::get('b2c')->_('到货通知'),'app'=>'b2c','ctl'=>'site_member','link'=>'notify'),
                        array('label'=>app::get('b2c')->_('我的优惠券'),'app'=>'b2c','ctl'=>'site_member','link'=>'coupon'),
                        $arr_blance,//预存款充值
//                        $arr_recharge_blance,//预存款充值
                        $arr_point_coupon_exchange,//积分兑换优惠券
                    ),
                ),
                array(
                    'label'=>app::get('b2c')->_('个人信息管理'),
                    'mid'=>4,
                    'items'=>array(
                        array('label'=>app::get('b2c')->_('站内信'),'app'=>'b2c','ctl'=>'site_member','link'=>'inbox'),
                        array('label'=>app::get('b2c')->_('个人信息'),'app'=>'b2c','ctl'=>'site_member','link'=>'setting'),
                        array('label'=>app::get('b2c')->_('安全中心'),'app'=>'b2c','ctl'=>'site_member','link'=>'securitycenter'),
                        array('label'=>app::get('b2c')->_('收货人'),'app'=>'b2c','ctl'=>'site_member','link'=>'consignee'),
                        array('label'=>app::get('b2c')->_('收货地址'),'app'=>'b2c','ctl'=>'site_member','link'=>'receiver'),
                        array('label'=>app::get('b2c')->_('付款人'),'app'=>'b2c','ctl'=>'site_member','link'=>'company'),
                    ),
                ),
//				array(
//					'label'=>app::get('b2c')->_('订单管理'),
//                    'mid'=>4,
//                    'items'=>array(
//                        array('label'=>app::get('b2c')->_('订单确认'),'app'=>'b2c','ctl'=>'site_member','link'=>'confirm'),
//                    ),
//				),
            );
        }
//        if(empty($arr_bases[1]) ){
//            unset($arr_bases[1]);
//        }

        //申请退换货的扩展
        if($this->pagedata['is_personal']== 0){
            $obj_menu_extends = kernel::servicelist('b2c.member_menu_extends');
            if ($obj_menu_extends)
            {
                foreach ($obj_menu_extends as $obj)
                {
                    if (method_exists($obj, 'get_extends_menu'))
                        $obj->get_extends_menu($arr_bases, array('0'=>'b2c', '1'=>'site_member', '2'=>'index'));
                }
            }
        }

        return $arr_bases;
    }

    /*
     *会员中心页面统一输出
     * */
    protected function output($app_id='b2c'){
        $this->pagedata['member'] = $this->member;
        $this->pagedata['cpmenu'] = $this->get_cpmenu();
        $this->pagedata['current'] = $this->action;
        if( $this->pagedata['_PAGE_'] ){
            $this->pagedata['_PAGE_'] = 'site/member/'.$this->pagedata['_PAGE_'];
        }else{
            $this->pagedata['_PAGE_'] = 'site/member/'.$this->action_view;
        }
        foreach(kernel::servicelist('member_index') as $service){
            if(is_object($service)){
                if(method_exists($service,'get_member_html')){
                    $aData[] = $service->get_member_html();
                }
            }
        }
        $this->pagedata['is_personal'];
        $this->pagedata['app_id'] = $app_id;
        $this->pagedata['_MAIN_'] = 'site/member/main.html';
        $this->pagedata['get_member_html'] = $aData;
        $this->set_tmpl('member');
        $this->page('site/member/main.html');
    }

    /**
     * 获取会员基本信息
     * edit by kim
     **/
    private function load_info(){
        $obj_member = &$this->app->model('members');
        $member_info = $obj_member->getList('*',array('member_id'=>$this->app->member_id));
        $member_info=$member_info[0];
        $this->member['user_type']=$member_info['user_type'];
        $this->pagedata['is_personal']=$this->member['user_type'];
        if($member_info['user_type']==1 && $member_info['is_main']==1 && $member_info['business_id']==0){
            $role_business = 1;//主账号
        }else{
            $role_business = 0;//子账号
        }
        $this->pagedata['role_business'] = $role_business;
    }


    /*
     *本控制器公共分页函数
     * */
    function pagination($current,$totalPage,$act,$arg='',$app_id='b2c',$ctl='site_member'){
        if (!$arg)
            $this->pagedata['pager'] = array(
                'current'=>$current,
                'total'=>$totalPage,
                'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>array(($tmp = time())))),
                'token'=>$tmp,
            );
        else
        {
            $arg = array_merge($arg, array(($tmp = time())));
            $this->pagedata['pager'] = array(
                'current'=>$current,
                'total'=>$totalPage,
                'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>$arg)),
                'token'=>$tmp,
            );
        }
    }

    function get_start($nPage,$count){
        $maxPage = ceil($count / $this->pagesize);
        if($nPage > $maxPage) $nPage = $maxPage;
        $start = ($nPage-1) * $this->pagesize;
        $start = $start<0 ? 0 : $start;
        $aPage['start'] = $start;
        $aPage['maxPage'] = $maxPage;
        return $aPage;
    }

    /*
     *会员中心首页
     * */
    public function index() {
        $this->pagedata['gys'] = $this->is_personal;
        $userObject = kernel::single('b2c_user_object');
        //面包屑
        if($this->pagedata['gys']==1){
            $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        }elseif($this->pagedata['gys']==2){
            $this->path[] = array('title'=>app::get('b2c')->_('集货员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        }else{
            $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        }

        $GLOBALS['runtime']['path'] = $this->path;

        #会员基本信息
        $this->member = $userObject->get_current_member();

        #获取会员等级
        $obj_mem_lv = $this->app->model('member_lv');
        $levels = $obj_mem_lv->getList('name,disabled',array('member_lv_id'=>$this->member['member_lv']));
        if($levels[0]['disabled']=='false'){
            $this->member['levelname'] = $levels[0]['name'];
        }
        $oMem_lv = $this->app->model('member_lv');
        $this->pagedata['switch_lv'] = $oMem_lv->get_member_lv_switch($this->member['member_lv']);

        //交易提醒
        $msgAlert = $this->msgAlert();
        $this->member = array_merge($this->member,$msgAlert);

        //订单列表
        $oRder = $this->app->model('orders');//--11sql
        $aData = $oRder->fetchByMember($this->app->member_id,$nPage=1,array(),5); //--141sql优化点
        //获取预售信息主要是时间219-231
        $prepare_order=kernel::service('prepare_order');
        if($prepare_order)
        {
            $pre_order=$prepare_order->get_prepare_info($aData['data']);
            foreach ($aData['data'] as $key => $value) {
                if($value['promotion_type']=='prepare')
                {
                    $aData['data'][$key]['prepare']=$pre_order[$value['order_id']];
                }
            }
        }

        $this->get_order_details($aData, 'member_latest_orders');//--177sql 优化点

        //是否存在付款单 by yyj 2015/10/20
        foreach ($aData['data'] as $key => $item){
            $pay = app::get('b2c')->model('payments');
            $aData['data'][$key]['is_pay'] = $pay->count(array('order_id'=>$item['order_id'],'status|noequal'=>'succ'));
        }

        //添加预售订单编号处理-----jyy
        foreach($aData['data'] as $key=>$val)
        {
            if($aData['data'][$key]['pre_order']=='true')
            {
                $aData['data'][$key]['pre_number'] = PRE_SALE.$val['pre_number'];
            }
        }
        $OrderModel_obj = $this->app->model('business_orders_objects');
        //增加供应商库存已确认，确认部分商品数量情况，增加待付款(有缺货)情况状态----jyy---2016/11/08
        foreach($aData['data'] as $key => $item){
            foreach($item['order_objects'] as $arr_objects){
                if($arr_objects['order_items']){
                    foreach($arr_objects['order_items'] as $arr_items){
                        if ($arr_items['item_type'] == 'product')
                        {
                            $objOrder = $OrderModel_obj->dump(array('goods_id'=>$arr_items['goods_id'],'mainOrder_id'=>$arr_items['order_id']),'*');
                            //计算已确认商品库存数量
                            if($item['c_status'] == '2'){
                                if($arr_items['quantity'] > $objOrder['has_confirm_num']){
                                    $aData['data'][$key]['c_status'] = '5';//待付款，有缺货
                                }
                            }

                        }
                        //计算重新确认后的商品总数量
                        $aData['data'][$key]['has_confirm_itemnum'] += $arr_items['has_confirm_num'];
						
						//for equaring 
					    $user_type_query = "SELECT `company_name` AS main_client_name,`company_inn` AS main_client_inn,`c_type` AS main_client_type FROM `sdb_b2c_members` WHERE `member_id` = ".$this->app->member_id;
						$user_type = kernel::database()->select($user_type_query);
						foreach($user_type as $u_k => $u_v){
							foreach($u_v as $u_k2 => $u_v2){
								$aData['data'][$key][$u_k2] = $u_v2;
								//fix other countries
								$serchRF = strpos($aData['data'][$key]['consignee']['area'], 'РФ/');
								
								if ($serchRF  === false) {
									$aData['data'][$key]['consignee']['RF'] = 0;
								} 
								else {
									$aData['data'][$key]['consignee']['RF'] = 1;
								}
								//fix Kaliningrad
								$serchKaliningrad = strpos($aData['data'][$key]['consignee']['area'], 'Калининград');			
								if ($serchKaliningrad === false) {
									$aData['data'][$key]['consignee']['kaliningrad'] = 0;
								} 
								else {
									$aData['data'][$key]['consignee']['kaliningrad'] = 1;
								}
							}
						}
                    }
                }

            }

            $aData['data'][$key]['nums'] = count($item['order_objects']);
        }

        $this->pagedata['orders'] = $aData['data'];

        //收藏列表
        $obj_member = $this->app->model('member_goods');
        $aData_fav = $obj_member->get_favorite($this->app->member_id,$this->member['member_lv'],$page=1,$num=5);//201sql
        $this->pagedata['favorite'] = $aData_fav['data'];
        #默认图片
        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];

        //汇款单 by yyj 2015/9/15
        $this->pagedata['image_dir'] = app::get('image')->res_url;
        $this->pagedata['session_id'] = kernel::single('base_session')->sess_id();
        $this->pagedata['res_dir'] = app::get('desktop')->res_url;
        $this->pagedata['IMAGE_MAX_SIZE'] = IMAGE_MAX_SIZE;


		
		
        //输出
        $this->pagedata['member'] = $this->member;
        $this->set_tmpl('member');
		
		
		//this is for alpha-bank pay autostatus 31/07/17 - Alfeev
		if(isset ($_GET['number']) && !empty($_GET['number'])){
			$order_number = trim(strip_tags($_GET['number']));
			if (preg_match('/^\+?\d+$/', $order_number)) { //success 
				if(trim($_GET['success']== '1')){
					$payUpdate = "UPDATE `sdb_b2c_orders` SET `pay_status` = '1' WHERE `order_id` = $order_number";
					$result = kernel::database()->query($payUpdate);
					header('Location: '.$_SERVER['PHP_SELF'].'?number='.$_GET['number'].'&orderId='.$_GET['orderId'].'&amount='.$_GET['amount']);
				}
				else{
					$this->pagedata['alphapay']['number'] = $order_number;
					$this->pagedata['alphapay']['status'] = 'success';
					$payed_amount = trim(strip_tags($_GET['amount']));
					$payed_amount = substr($payed_amount,0,-2);
					$payed_amount = number_format($payed_amount, 0, '',' ');
					$this->pagedata['alphapay']['amount'] = $payed_amount;
				}
				
			}
			else{ //error
				$this->pagedata['alphapay']['number'] = $order_number;
				$this->pagedata['alphapay']['status'] = 'error';
			}
		}
		
        $this->output();
		
		

		
    }

    /*
     *会员中心首页交易提醒 (未付款订单,到货通知，未读的评论咨询回复)
     * */
    private function msgAlert(){
        //获取待付款订单数
        $oRder = $this->app->model('orders');//--11sql
        $un_pay_orders = $oRder->count(array('member_id' => $this->member['member_id'],'pay_status' => 0,'status'=>'active','promotion_type' => 'normal'));
        $member['un_pay_orders'] = $un_pay_orders;
        //获取预售订单数----jyy修改为新预售订单统计数量
        $prepare_pay_orders = $oRder->count(array('member_id' => $this->member['member_id'],'pre_order' => 'true'));
        $member['prepare_pay_orders'] = $prepare_pay_orders;
        //到货通知
        $member_goods = $this->app->model('member_goods');
        $member['sto_goods_num'] = $member_goods->get_goods($this->app->member_id);

        //评论咨询回复
        $mem_msg = $this->app->model('member_comments');
        $object_type = array('discuss','ask');
        $aData = $mem_msg->getList('*',array('to_id' => $this->app->member_id,'object_type'=> $object_type,'mem_read_status' => 'false','display' => 'true'));
        $un_readAskMsg = 0;
        $un_readDiscussMsg = 0;
        foreach($aData as $val){
            if($val['object_type'] == 'ask'){
                $un_readAskMsg += 1;
            }else{
                $un_readDiscussMsg += 1;
            }
        }
        $member['un_readAskMsg'] = $un_readAskMsg;
        $member['un_readDiscussMsg'] = $un_readDiscussMsg;
        return $member;
    }



    function setting(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('个人信息'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $userObject = kernel::single('b2c_user_object');
        $membersData = $userObject->get_pam_data('*',$this->app->member_id);
        $this->pagedata['mem'] = $membersData;

        //修改用户名埋点
        //if(app::get('pam')->model('members')->is_openIdNameByName($this->pagedata['mem']['local']) == true) $this->pagedata['allowtochangeusername'] = true;

        $attr = kernel::single('b2c_user_passport')->get_signup_attr($this->app->member_id);
        $this->pagedata['attr'] = $attr;
        $this->output();
    }

    function save_setting(){
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>"site_member",'act'=>"setting"));
        $member_model = $this->app->model('members');
        $userPassport = kernel::single('b2c_user_passport');
        $_POST = $this->check_input($_POST);
        if($_POST['local_name'] && !$userPassport->set_local_uname($_POST,$msg)){
            $this->splash('failed',null , $msg,true);
        }

        foreach($_POST as $key=>$val){
            if(strpos($key,"box:") !== false){
                $aTmp = explode("box:",$key);
                $_POST[$aTmp[1]] = serialize($val);
            }
        }


        //--防止恶意修改
        $arr_colunm = array('contact','profile','pam_account','currency');
        $attr = $this->app->model('member_attr')->getList('attr_column');
        foreach($attr as $attr_colunm){
            $colunm = $attr_colunm['attr_column'];
            $arr_colunm[] = $colunm;
        }
        foreach($_POST as $post_key=>$post_value){
            if( !in_array($post_key,$arr_colunm) ){
                unset($_POST[$post_key]);
            }
        }
        //---end

        $_POST['member_id'] = $this->app->member_id;
        if($member_model->save($_POST)){

            //增加会员同步 2012-05-15
            if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
                $member_rpc_object->modifyActive($_POST['member_id']);
            }

            $this->splash('success', $url , app::get('b2c')->_('提交成功'),true);
        }else{
            $this->splash('failed',null , app::get('b2c')->_('提交失败'),true);
        }
    }

    //修改用户名埋点
    //public function change_member_name(){
    //    $member_id    = $this->member['member_id'];
    //    $member_name  = $_POST['local_name'];
    //    $userPassport = kernel::single('b2c_user_passport');
    //    $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'setting'));
    //    if($userPassport->change_member_name($member_id, $member_name, $msg))
    //        $this->splash('success', $url, app::get('b2c')->_('提交成功'), true);
    //    $this->splash('failed', null, $msg, true);
    //  //$this->splash('failed', null,$userPassport->change_member_name($member_id, $member_name, $msg), true);
    //}

    /**
     * Member order list datasource
     * @params int equal to 1
     * @return null
     */
    public function orders($pay_status='all', $nPage=1)
    {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('我的订单'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $order = $this->app->model('orders');
        if ($pay_status == 'all')
        {
            $aData = $order->fetchByMember($this->app->member_id,$nPage);
        }
        else
        {
            $order_status = array();
            if ($pay_status == 'nopayed')
            {   $order_status['promotion_type'] = 'normal';
                $order_status['pay_status'] = 0;
                $order_status['status'] = 'active';
            }
            if($pay_status == 'prepare')
            {
                //$order_status['pay_status'] = 1;
                //$order_status['status'] = 'active';
                $order_status['promotion_type'] = 'prepare';
            }
            $aData = $order->fetchByMember($this->app->member_id,$nPage-1,$order_status);
        }
        $this->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $imageDefault = app::get('image')->getConf('image.set');
        foreach($aData['data'] as $k => &$v) {
            foreach($v['goods_items'] as $k2 => &$v2) {
                $spec_desc_goods = $oGoods->getList('spec_desc',array('goods_id'=>$v2['product']['goods_id']));
                $select_spec_private_value_id = reset($v2['product']['products']['spec_desc']['spec_private_value_id']);
                $spec_desc_goods = reset($spec_desc_goods[0]['spec_desc']);
                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                    $v2['product']['thumbnail_pic'] = $default_product_image;
                }else{
                    if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                        $v2['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                    }
                }
            }
        }
        //获取预售信息主要是时间390-398
        $prepare_order=kernel::service('prepare_order');
        if($prepare_order)
        {
            $pre_order=$prepare_order->get_prepare_info($aData['data']);
            foreach ($aData['data'] as $key => $value) {
                if($value['promotion_type']=='prepare')
                {
                    $aData['data'][$key]['prepare']=$pre_order[$value['order_id']];
                }

            }
        }

        //是否存在付款单 by yyj 2015/10/20
        foreach ($aData['data'] as $key => $item){
            $pay = app::get('b2c')->model('payments');
            $aData['data'][$key]['is_pay'] = $pay->count(array('order_id'=>$item['order_id'],'status|noequal'=>'succ'));
        }

        //添加预售订单编号处理-----jyy
//            foreach($aData['data'] as $key=>$val)
//            {
//                if($aData['data'][$key]['pre_order']=='true'){
//                    $aData['data'][$key]['pre_number'] = PRE_SALE.$val['pre_number'];
//                }
//            }
        $OrderModel_obj = $this->app->model('business_orders_objects');
        //增加供应商库存已确认，确认部分商品数量情况，增加待付款(有缺货)情况状态----jyy---2016/11/08
        $aData['data'][$key]['itemnum'] = 0;
        foreach($aData['data'] as $key => $item){
            foreach($item['order_objects'] as $arr_objects){
                if($arr_objects['order_items']){
                    foreach($arr_objects['order_items'] as $arr_items){
                        if ($arr_items['item_type'] == 'product')
                        {
                            $objOrder = $OrderModel_obj->dump(array('goods_id'=>$arr_items['goods_id'],'mainOrder_id'=>$arr_items['order_id']),'*');
                            //计算已确认商品库存数量
                            if($item['c_status'] == '2'){
                                if($arr_items['quantity'] > $objOrder['has_confirm_num']){
                                    $aData['data'][$key]['c_status'] = '5';//待付款，有缺货
                                }
                            }
                        }
                        //计算重新确认后的商品总数量
                        $aData['data'][$key]['has_confirm_itemnum'] += $arr_items['has_confirm_num'];
						
						//for equaring 
					    $user_type_query = "SELECT `company_name` AS main_client_name,`company_inn` AS main_client_inn,`c_type` AS main_client_type FROM `sdb_b2c_members` WHERE `member_id` = ".$this->app->member_id;
						$user_type = kernel::database()->select($user_type_query);
						foreach($user_type as $u_k => $u_v){
							foreach($u_v as $u_k2 => $u_v2){
								$aData['data'][$key][$u_k2] = $u_v2;
								
								//fix other countries
								$serchRF = strpos($aData['data'][$key]['consignee']['area'], 'РФ/');
								
								if ($serchRF  === false) {
									$aData['data'][$key]['consignee']['RF'] = 0;
								} 
								else {
									$aData['data'][$key]['consignee']['RF'] = 1;
								}
								
								//fix Kaliningrad
								$serchKaliningrad = strpos($aData['data'][$key]['consignee']['area'], 'Калининград');
								if ($serchKaliningrad === false) {
									$aData['data'][$key]['consignee']['kaliningrad'] = 0;
								} 
								else {
									$aData['data'][$key]['consignee']['kaliningrad'] = 1;
								}
								
								
							}
						}
                    }
                }
            }

         //echo '<div class="hide"><pre>';
          //print_r($aData);
         //echo '</pre></div>';
            //exit();
        }


        $this->pagedata['orders'] = $aData['data'];


        $arr_args = array($pay_status);
        $this->pagination($nPage,$aData['pager']['total'],'orders',$arr_args);
        $this->pagedata['res_url'] = $this->app->res_url;
        $this->pagedata['is_orders'] = "true";

        //汇款单 by yyj 2015/9/14
        $this->pagedata['image_dir'] = app::get('image')->res_url;
        $this->pagedata['session_id'] = kernel::single('base_session')->sess_id();
        $this->pagedata['res_dir'] = app::get('desktop')->res_url;
        $this->pagedata['IMAGE_MAX_SIZE'] = IMAGE_MAX_SIZE;
		
		//this is for alpha-bank pay autostatus 21/02/17 - Alfeev
		if(isset ($_GET['number']) && !empty($_GET['number'])){
			$order_number = trim(strip_tags($_GET['number']));
			if (preg_match('/^\+?\d+$/', $order_number)) { //success 
				if(trim($_GET['success']== '1')){
					$payUpdate = "UPDATE `sdb_b2c_orders` SET `pay_status` = '1' WHERE `order_id` = $order_number";
					$result = kernel::database()->query($payUpdate);
					header('Location: '.$_SERVER['PHP_SELF'].'?number='.$_GET['number'].'&orderId='.$_GET['orderId'].'&amount='.$_GET['amount']);
				}
				else{
					$this->pagedata['alphapay']['number'] = $order_number;
					$this->pagedata['alphapay']['status'] = 'success';
					$payed_amount = trim(strip_tags($_GET['amount']));
					$payed_amount = substr($payed_amount,0,-2);
					$payed_amount = number_format($payed_amount, 0, '',' ');
					$this->pagedata['alphapay']['amount'] = $payed_amount;
				}
				
			}
			else{ //error
				$this->pagedata['alphapay']['number'] = $order_number;
				$this->pagedata['alphapay']['status'] = 'error';
			}
		}
		

        $this->output();
    }

    /**
     * 动态的swf页面显示 by yyj 2015/9/15
     * @param null
     * @return string html内容
     */
    function gimage_swf_remote(){
        $image = app::get('image')->model('image');
        $image_attach = app::get('image')->model('image_attach');
        $image_name = $_FILES['Filedata']['name'];

        $image_data = $image->store2($_FILES['Filedata']['tmp_name'],null,null,$image_name);
        $image_id = $image_data['image_id'];
        $image_url = $image_data['url'];

        $sData = array(
            'target_id'=>$_GET['order_id'],
            'target_type'=>'orders',
            'image_id'=>$image_id,
            'last_modified'=>time(),
        );
        $image_attach->save($sData);

        $image->rebuild($image_id,array('L','M','S'));

        $this->pagedata['gimage']['image_id'] = $image_id;
        $this->pagedata['gimage']['image_url'] = $image_url;

//            header('Content-Type:text/html; charset=utf-8');
        echo $this->fetch('site/member/img/gimage.html');
    }

    /**
     * 删除图片 by yyj 2015/9/15
     * @param nulll
     * @return string html页面内容
     */
    function del_image(){
        $oImage = app::get('image')->model('image');
        $image_attach = app::get('image')->model('image_attach');
        if($oImage->delete_image($_POST['image_id'],$_POST['order_id'])){
            $filter = array(
                'target_id'=>$_POST['order_id'],
                'image_id'=>$_POST['image_id'],
                'target_type'=>'orders',
            );
            $image_attach->delete($filter);
            $arr_json_data = array('success'=> '删除图片完成');
            echo json_encode($arr_json_data);exit;
        }else{
            echo '{error:删除图片失败}';
            exit;
        }
    }

    /**
     * Member order list datasource
     * @params int equal to 1
     * @return null
     */
    public function archive_orders($pay_status='all', $nPage=1)
    {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('我的订单'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $order = $this->app->model('archive_orders');
        $aData = $order->fetchByMember($this->app->member_id,$nPage-1);

        $this->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $imageDefault = app::get('image')->getConf('image.set');
        foreach($aData['data'] as $k=>$v) {
            foreach($v['goods_items'] as $k2=>$v2) {
                if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                    $aData['data'][$k]['goods_items'][$k2]['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                }
            }
        }
        $this->pagedata['orders'] = $aData['data'];

        $arr_args = array('all');
        $this->pagination($nPage,$aData['pager']['total'],'archive_orders',$arr_args);
        $this->pagedata['res_url'] = $this->app->res_url;
        $this->pagedata['is_orders'] = "true";
        $this->pagedata['archive'] = true;
        $this->action_view = 'orders.html';
        $this->output();
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string tpl
     * @return null
     */
    protected function get_order_details(&$aData,$tml='member_orders')
    {
        if (isset($aData['data']) && $aData['data'])
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }

            foreach ($aData['data'] as &$arr_data_item)
            {
                $this->get_order_detail_item($arr_data_item,$tml);

                //add by yyj 2015/9/15
                $image_attach = app::get('image')->model('image_attach');
                $image = app::get('image')->model('image');
                $image_ids = $image_attach->getList('image_id',array('target_id'=>$arr_data_item['order_id'],'target_type'=>'orders'));
                $ids = array();
                foreach($image_ids as $key => $id){
                    $ids[$key] = $id['image_id'];
                }
                $iData = $image->getList('image_id,url as image_url',array('image_id|in'=>$ids));
                $arr_data_item['images'] = $iData;
            }
        }
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string 模版名称
     * @return null
     */
    protected function get_order_detail_item(&$arr_data_item,$tpl='member_order_detail')
    {
        if (isset($arr_data_item) && $arr_data_item)
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }


            $arr_data_item['goods_items'] = array();
            $obj_specification = $this->app->model('specification');
            $obj_spec_values = $this->app->model('spec_values');
            $obj_goods = $this->app->model('goods');
            if (isset($arr_data_item['order_objects']) && $arr_data_item['order_objects'])
            {
                foreach ($arr_data_item['order_objects'] as $k=>$arr_objects)
                {
                    $index = 0;
                    $index_adj = 0;
                    $index_gift = 0;
                    $image_set = app::get('image')->getConf('image.set');
                    if ($arr_objects['obj_type'] == 'goods')
                    {
                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            if (!$arr_items['products'])
                            {
                                $o = $this->app->model('order_items');
                                $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                $arr_items['products']['product_id'] = $tmp[0]['product_id'];
								
                            }
	
                            if ($arr_items['item_type'] == 'product')
                            {
                                if ($arr_data_item['goods_items'][$k]['product'])
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k]['product']['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $arr_items['quantity'];

                                $arr_data_item['goods_items'][$k]['product'] = $arr_items;
                                $arr_data_item['goods_items'][$k]['product']['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k]['product']['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k]['product']['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k]['product']['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k]['product']['quantity']);
                                $arr_data_item['goods_items'][$k]['product']['amount'] = $arr_items['amount'];
                                $arr_goods_list = $obj_goods->getList('unit_num,image_default_id,params', array('goods_id' => $arr_items['goods_id']));
                                $arr_goods = $arr_goods_list[0];
                                //-------------liuyulei 获取订单的商品价格--------
                                $arr_data_item['goods_items'][$k]['product']['sale_price'] = $arr_items['goods_price'];
                                $arr_data_item['goods_items'][$k]['product']['one_price'] = round($arr_items['goods_price']/$arr_goods['unit_num']);
                                //-------------liuyulei 获取订单的商品价格 end--------
								//-------------A.Alfeev 11.08.17--------
                                $arr_data_item['goods_items'][$k]['product']['unit_num'] = $arr_goods['unit_num'];
								$pairs_per_box_arr = array();
								foreach($arr_goods['params']["Размерный ряд"] as $p_k => $p_v){
									if(!empty($p_v)){
										if($p_k != "Кол-во в упаковке"){
											$pairs_per_box_arr[$p_k] = $p_v;
										}
									}
								}	
                                $arr_data_item['goods_items'][$k]['product']['params'] = $pairs_per_box_arr;
                                //-------------A.Alfeev 11.08.17 end--------
                                if (!$arr_goods['image_default_id'])
                                {
                                    $arr_goods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k]['product']['thumbnail_pic'] = $arr_goods['image_default_id'];
                                $arr_data_item['goods_items'][$k]['product']['link_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id']));;
                                if ($arr_items['addon'])
                                {
                                    $arrAddon = $arr_addon = unserialize($arr_items['addon']);
                                    if ($arr_addon['product_attr'])
                                        unset($arr_addon['product_attr']);
                                    $arr_data_item['goods_items'][$k]['product']['minfo'] = $arr_addon;
                                }else{
                                    unset($arrAddon,$arr_addon);
                                }
                                if ($arrAddon['product_attr'])
                                {
                                    foreach ($arrAddon['product_attr'] as $arr_product_attr)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k]['product']['attr']) && $arr_data_item['goods_items'][$k]['product']['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k]['product']['attr'], " ") !== false)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] = substr($arr_data_item['goods_items'][$k]['product']['attr'], 0, strrpos($arr_data_item['goods_items'][$k]['product']['attr'], $this->app->_(" ")));
                                    }
                                }
                            }
                            elseif ($arr_items['item_type'] == 'adjunct')
                            {
                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);


                                if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj])
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $arr_items['quantity'];

                                if (!$arrGoods['image_default_id'])
                                {
                                    $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj] = $arr_items;
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']);
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['link_url'] = $arrGoods['link_url'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['amount'] = $arr_items['amount'];

                                if ($arr_items['addon'])
                                {
                                    $arr_addon = unserialize($arr_items['addon']);

                                    if ($arr_addon['product_attr'])
                                    {
                                        foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                        }
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")) !== false)
                                    {
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")));
                                    }
                                }

                                $index_adj++;
                            }
                            else
                            {
                                // product gift.
                                if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                                {
                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift])
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift] = $arr_items;
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['name'] = $arr_items['name'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['price'] = $arr_items['price'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity']);
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'])
                                    {
                                        if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                                $index_gift++;
                            }
                        }
                    }
                    else
                    {
                        if ($arr_objects['obj_type'] == 'gift')
                        {
                            //积分兑换赠品
                            $gift_key = '';
                            if( $arr_objects['obj_alias'] == app::get('b2c')->_('商品区块') ){
                                $gift_key = 'gift';//积分兑换赠品
                            }else{
                                $gift_key = 'order'; //订单送赠品，包含优惠券送赠品
                            }
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {
                                foreach ($arr_objects['order_items'] as $arr_items)
                                {
                                    if (!$arr_items['products'])
                                    {
                                        $o = $this->app->model('order_items');
                                        $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                        $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                                    }

                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if (!isset($arr_items['products']['product_id']) || !$arr_items['products']['product_id'])
                                        $arr_items['products']['product_id'] = $arr_items['goods_id'];

                                    if ($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']])
                                        $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }

                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['name'] = $arr_items['name'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['price'] = $arr_items['price'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['point'] = intval($arr_items['score']*$arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']);
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['nums'] = $arr_items['quantity'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr']) && $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'])
                                    {
                                        if (strpos($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] = substr($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], 0, strrpos($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {

                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                $arr_data_item['extends_items'][] = $str_service_goods_type_obj->get_order_object($arr_objects, $arr_Goods,$tpl);
                            }
                        }
                    }
                }
            }
        }
		
	
    }

    /**
     * Generate the order detail
     * @params string order_id
     * @return null
     */
    public function orderdetail($order_id=0, $archive=false)
    {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('我的订单'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'orders','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('订单详情'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        if (!isset($order_id) || !$order_id)
        {
            $this->begin(array('app' => 'b2c','ctl' => 'site_member', 'act'=>'index'));
            $this->end(false, app::get('b2c')->_('订单编号不能为空！'));
        }

        $objOrder = $archive ? $this->app->model('archive_orders') : $this->app->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))), 'order_pmt'=>array('*'));
        $sdf_order = $objOrder->dump(array('order_id'=>$order_id), '*', $subsdf);
        $objMath = kernel::single("ectools_math");

        if(!$sdf_order||$this->app->member_id!=$sdf_order['member_id']){
            kernel::single('site_router')->http_status(404);return;
        }
        if($sdf_order['member_id']){
            $member = $this->app->model('members');
            $aMember = $member->dump($sdf_order['member_id'], 'email');
            $sdf_order['receiver']['email'] = $aMember['contact']['email'];
        }

        // 处理收货人地区
        $arr_consignee_area = array();
        $arr_consignee_regions = array();
        if (strpos($sdf_order['consignee']['area'], ':') !== false)
        {
            $arr_consignee_area = explode(':', $sdf_order['consignee']['area']);
            if ($arr_consignee_area[1])
            {
                if (strpos($arr_consignee_area[1], '/') !== false)
                {
                    $arr_consignee_regions = explode('/', $arr_consignee_area[1]);
                }
            }

            $sdf_order['consignee']['area'] = (is_array($arr_consignee_regions) && $arr_consignee_regions) ? $arr_consignee_regions[0] . ' '.$arr_consignee_regions[1] .' '. $arr_consignee_regions[2] : $sdf_order['consignee']['area'];
        }

        // 订单的相关信息的修改
        $obj_other_info = kernel::servicelist('b2c.order_other_infomation');
        if ($obj_other_info)
        {
            foreach ($obj_other_info as $obj)
            {
                $this->pagedata['discount_html'] = $obj->gen_point_discount($sdf_order);
            }
        }
	// echo '<pre>';print_R($sdf_order);exit();
        $this->pagedata['order'] = $sdf_order;

        $order_items = array();
        $gift_items = array();
        $this->get_order_detail_item($sdf_order,'member_order_detail');

//        //处理预售订单最早到货日期和最晚到货日期-----jyy
//        if ($sdf_order['pre_order'] == 'true')
//        {
//            //处理预售订单编号----加前缀P
//            $sdf_order['pre_number'] = PRE_SALE.$sdf_order['pre_number'];
//            //处理预售订单到货日期
//
//            //依据预售单id，查询商品goods_id;
//            $product_id_arr = app::get('b2c')->model('order_items')->getList('product_id,goods_id',array('order_id'=>$order_id));
//            foreach($product_id_arr as $key => $v)
//            {
//                //依据商品goods_id，查询预售商品到货日期
//                $arrival_time_arr = app::get('b2c')->model('goods')->getList('arrival_time',array('goods_id'=>$v['goods_id']));
//                //遍历循环到货日期
//                foreach ($arrival_time_arr as $key => $val)
//                {
//                    $arrival_time[] = $val['arrival_time'];
//                }
//            }
//           //最早到货日期
//           $sdf_order['first_date'] = date('d-m-Y',min($arrival_time));
//           //最晚到货日期
//           $sdf_order['last_date'] = date('d-m-Y',max($arrival_time));
//           unset($arrival_time);
//        }

        $this->pagedata['order'] = $sdf_order;
        /** 将商品促销单独剥离出来 **/
        if ($this->pagedata['order']['order_pmt'])
        {
            foreach ($this->pagedata['order']['order_pmt'] as $key=>$arr_pmt)
            {
                if ($arr_pmt['pmt_type'] == 'goods')
                {
                    $this->pagedata['order']['goods_pmt'][$arr_pmt['product_id']][$key] =  $this->pagedata['order']['order_pmt'][$key];
                    unset($this->pagedata['order']['order_pmt'][$key]);
                }
            }
        }
        /** end **/

        // 得到订单留言.
        $oMsg = kernel::single("b2c_message_order");
        $arrOrderMsg = $oMsg->getList('*', array('order_id' => $order_id, 'object_type' => 'order'), $offset=0, $limit=-1, 'time DESC');

        $this->pagedata['ordermsg'] = $arrOrderMsg;
        $this->pagedata['res_url'] = $this->app->res_url;

        //我已付款
        $$timeHours = array();
        for($i=0;$i<24;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeHours[$v] = $v;
        }
        $timeMins = array();
        for($i=0;$i<60;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeMins[$v] = $v;
        }
        $this->pagedata['timeHours'] = $timeHours;
        $this->pagedata['timeMins'] = $timeMins;

        // 生成订单日志明细
        //$oLogs =$this->app->model('order_log');
        //$arr_order_logs = $oLogs->getList('*', array('rel_id' => $order_id));
        $arr_order_logs = $objOrder->getOrderLogList($order_id);
        $this->pagedata['orderlogs'] = $arr_order_logs['data'];

        // 取到支付单信息
        $obj_payments = app::get('ectools')->model('payments');
        $this->pagedata['paymentlists'] = $obj_payments->get_payments_by_order_id($order_id);

        // 支付方式的解析变化
        $obj_payments_cfgs = app::get('ectools')->model('payment_cfgs');
        $arr_payments_cfg = $obj_payments_cfgs->getPaymentInfo($this->pagedata['order']['payinfo']['pay_app_id']);
        $this->pagedata['order']['payment'] = $arr_payments_cfg;

        // 添加html埋点
        foreach( kernel::servicelist('b2c.order_add_html') as $services ) {
            if ( is_object($services) ) {
                if ( method_exists($services, 'fetchHtml') ) {
                    $services->fetchHtml($this,$order_id,'site/invoice_detail.html');
                }
            }
        }
        $this->pagedata['controller'] = "orders";
        $this->pagedata['archive'] = $archive;
        // 预售订单信息
        $prepare_order=kernel::service('prepare_order');
        if($prepare_order)
        {
            $pre_order=$prepare_order->get_order_info($order_id);
            if(!empty($pre_order))
            {
                $pre_order['prepare_type']='prepare';
                $this->pagedata['prepare']=$pre_order;
            }
        }
        foreach($this->pagedata['order']['goods_items'] as $key=>$value){
            $this->pagedata['order']['goods_items'][$key]['product']['products']['price']['price']['s_price']=round($this->pagedata['order']['goods_items'][$key]['product']['products']['price']['price']['s_price']);
        }
        //echo '<pre>';print_r($prepare_order);exit();


        $sum = 0;
        $orderMdl =  app::get('b2c')->model('business_orders_objects')->getList('*',array('mainOrder_id'=>$order_id));

        foreach($orderMdl as $value){
            $tmm[$value['goods_id']] = $value;
            $sum += $value['amount'];
        }


        //print_r($orderMdl);
        $this->pagedata['business_orders_amount']=$sum;
// print_r($tmm);
        $this->pagedata['business_order']=$tmm;

        //----------liuyulei退还金额----
//        $obj_orders_objects = app::get('b2c')->model('business_orders_objects');
//        $orders_objects = $obj_orders_objects->getList('quantity,has_confirm_num,order_refund',array('state'=>1,'mainOrder_id'=>$sdf_order['order_id']));
//        if($orders_objects){
//            $order_refund = 0;
//            foreach($orders_objects as $_k=>$_v){
//                if($_v['quantity'] != $_v['has_confirm_num']) {
//                    $order_refund += ($_v['quantity'] - $_v['has_confirm_num'])*$_v['order_refund'];
//                }
//            }
//            $this->pagedata['order']['order_refund'] = $order_refund;
//        }
        //$this->pagedata['order']['order_refund'] = round($this->pagedata['business_orders_amount'] - $this->pagedata['order']['cost_item']);
        $this->pagedata['order']['order_refund'] = round($sum - $sdf_order['cost_item']);
        //----------liuyulei退还金额 end----

        $this->output();
    }

    function deposit(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('预存款充值'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $oCur = app::get('ectools')->model('currency');
        $currency = $oCur->getDefault();
        $this->pagedata['currencys'] = $currency;
        $this->pagedata['currency'] = $currency['cur_code'];
        $opay = app::get('ectools')->model('payment_cfgs');
        $aOld = $opay->getList('*', array('status' => 'true', 'platform'=>array('iscommon','ispc'), 'is_frontend' => true));

        #获取默认的货币
        $obj_currency = app::get('ectools')->model('currency');
        $arr_def_cur = $obj_currency->getDefault();
        $this->pagedata['def_cur_sign'] = $arr_def_cur['cur_sign'];

        $aData = array();
        foreach($aOld as $val){
            if(($val['app_id']!='deposit') && ($val['app_id']!='offline')){
                $aData[] = $val;
            }
        }

        $membersData = kernel::single('b2c_user_object')->get_members_data(array('members'=>'advance'));
        $this->pagedata['total'] = $membersData['members']['advance'];
        $this->pagedata['payments'] = $aData;
        $this->pagedata['member_id'] = $this->app->member_id;
        $this->pagedata['return_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'balance'));

        $this->output();
    }

    public function balance($nPage=1)
    {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('我的预存款'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $member = $this->app->model('members');
        $mem_adv = $this->app->model('member_advance');
        $items_adv = $mem_adv->get_list_bymemId($this->app->member_id);
        $count = count($items_adv);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $mem_adv->getList('*',array('member_id' => $this->app->member_id),$aPage['start'],$this->pagesize,'mtime desc');
        $params['page'] = $aPage['maxPage'];
        $this->pagination($nPage,$params['page'],'balance');
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['advlogs'] = $params['data'];
        $data = $member->dump($this->app->member_id,'advance');
        $this->pagedata['total'] = $data['advance']['total'];
        // errorMsg parse.
        $this->pagedata['errorMsg'] = json_decode($_GET['errorMsg']);
        $this->output();
    }

    /*
     *会员中心 商品收藏
     * */
    function favorite($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('商品收藏'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $membersData = kernel::single('b2c_user_object')->get_members_data(array('members'=>'member_lv_id'));
        $aData = kernel::single('b2c_member_fav')->get_favorite($this->app->member_id,$membersData['members']['member_lv_id'],$nPage);
        $imageDefault = app::get('image')->getConf('image.set');
        $aProduct = $aData['data'];
        foreach($aProduct as $k=>$v){
            if($v['nostore_sell']){
                $aProduct[$k]['store'] = 999999;
                $aProduct[$k]['product_id'] = $v['spec_desc_info'][0]['product_id'];
            }else{
                foreach((array)$v['spec_desc_info'] as $value){
                    $aProduct[$k]['product_id'] = $value['product_id'];
                    $aProduct[$k]['spec_info'] = $value['spec_info'];
                    $aProduct[$k]['price'] = $value['price'];
                    if(is_null($value['store']) ){
                        $aProduct[$k]['store'] = 999999;
                        break;
                    }elseif( ($value['store']-$value['freez']) > 0 ){
                        $aProduct[$k]['store'] = $value['store']-$value['freez'];
                        break;
                    }else{
                        $aProduct[$k]['store'] = false;
                    }
                }
            }
        }
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['favorite'] = $aProduct;
        $this->pagination($nPage,$aData['page'],'favorite');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $setting['buytarget'] = $this->app->getConf('site.buy.target');
        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;
        $this->pagedata['setting'] = $setting;
        $this->pagedata['current_page'] = $nPage;
        /** 接触收藏的页面地址 **/
        $this->pagedata['fav_ajax_del_goods_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'ajax_del_fav','args'=>array('goods')));
        $this->output();
    }

    /*
     *删除商品收藏
     * */
    function ajax_del_fav($gid=null,$object_type='goods'){
        if(!$gid){
            $this->splash('error',null,app::get('b2c')->_('参数错误！'),true);
        }

        if($_POST['response_json']){//取消收藏 by yyj 2015/12/21
            $member_goods = app::get('b2c')->model('member_goods');
            if($member_goods->delete(array('goods_id'=>$gid,'member_id'=>$this->app->member_id,'type'=>'fav'))){
                $this->set_cookie('S[GFAV]'.'['.$this->app->member_id.']',$this->get_member_fav($this->app->member_id),false);
                $this->splash('success',null,app::get('b2c')->_('成功移除！'),array('request'=>true));
            }else{
                $this->splash('error',null,app::get('b2c')->_('移除失败！'));
            }
        }else{
            if (!kernel::single('b2c_member_fav')->del_fav($this->app->member_id,$object_type,$gid,$maxPage)){
                $this->splash('error',null,app::get('b2c')->_('移除失败！'));
            }else{
                $this->set_cookie('S[GFAV]'.'['.$this->app->member_id.']',$this->get_member_fav($this->app->member_id),false);

                $current_page = $_POST['current'];
                if ($current_page > $maxPage){
                    $current_page = $maxPage;
                    $reload_url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'favorite','args'=>array($current_page)));
                    $this->splash('success',$url,app::get('b2c')->_('成功移除！'),true);
                }
                $aData = kernel::single('b2c_member_fav')->get_favorite($this->app->member_id,$this->member['member_lv'],$current_page);
                $aProduct = $aData['data'];

                $oImage = app::get('image')->model('image');
                $imageDefault = app::get('image')->getConf('image.set');
                foreach($aProduct as $k=>$v) {
                    if(!$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                        $aProduct[$k]['image_default_id'] = $imageDefault['S']['default_image'];
                    }
                }
                $this->pagedata['favorite'] = $aProduct;
                $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
                $this->splash('success',$url,app::get('b2c')->_('成功移除！'),array('request'=>true));
            }
        }
    }

    function ajax_fav() {
        $object_type = $_POST['type'];
        $nGid = $_POST['gid'];
        if (!kernel::single('b2c_member_fav')->add_fav($this->app->member_id,$object_type,$nGid)){
            $this->splash('failed', app::get('b2c')->_('商品收藏添加失败！'), '', '', true);
        }else{
            $this->set_cookie('S[GFAV]'.'['.$this->app->member_id.']',$this->get_member_fav($this->app->member_id),false);
            $this->splash('success',$url,app::get('b2c')->_('商品收藏添加成功'),array('request'=>true));
        }
    }

    /*
     *获取未读信息数目
     * */
    function get_unreadmsg_num(){
        $oMsg = kernel::single('b2c_message_msg');
        $num  = $oMsg->count(array('to_id' => $this->app->member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false'));
        $data['inbox_num'] = $num ? $num : 0;
        echo json_encode($data);
    }
    /*
     *获取收件箱未读信息数量
     * */
    function get_msg_num(){
        $oMsg = kernel::single('b2c_message_msg');
        $row = $oMsg->getList('*',array('to_id' => $this->app->member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false'));
        $this->pagedata['inbox_num'] = count($row)?count($row):0;
        $row = $oMsg->getList('*',array('has_sent' => 'false','author_id' => $this->app->member_id));
        $this->pagedata['outbox_num'] = count($row)?count($row):0;
    }
    //收件箱
    function inbox($nPage=1) {
        $this->get_msg_num();
        $oMsg = kernel::single('b2c_message_msg');
        $row = $oMsg->getList('*',array('to_id' => $this->app->member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true','mem_read_status' => 'false'));
        $this->pagedata['inbox_num'] = count($row)?count($row):0;

        $row = $oMsg->getList('*',array('to_id' => $this->app->member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' => 'true'));
        $aData['data'] = $row;
        $aData['total'] = count($row);
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('to_id' => $this->app->member_id,'has_sent' => 'true','for_comment_id' => 'all','inbox' =>'true'),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['message'] = $params['data'];
        $this->pagedata['total_msg'] = $aData['total'];
        $this->pagination($nPage,$params['page'],'inbox');
        $this->output();
    }

    //草稿箱
    function outbox($nPage=1) {
        $this->get_msg_num();
        $oMsg = kernel::single('b2c_message_msg');
        $row = $oMsg->getList('*',array('has_sent' => 'false','author_id' => $this->app->member_id));
        $aData['data'] = $row;
        $aData['total'] = count($row);
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('has_sent' => 'false','author_id' => $this->app->member_id),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['message'] = $params['data'];
        $this->pagedata['total_msg'] = $aData['total'];
        $this->pagination($nPage,$params['page'],'outbox');
        $this->pagedata['controller'] = "inbox";
        $this->output();
    }

    //已发送
    function track($nPage=1) {
        $this->get_msg_num();
        $oMsg = kernel::single('b2c_message_msg');
        $row = $oMsg->getList('*',array('author_id' => $this->app->member_id,'has_sent' => 'true','track' => 'true'));
        $aData['data'] = $row;
        $aData['total'] = count($row);
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('author_id' => $this->app->member_id,'has_sent' => 'true','track' => 'true'),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['message'] = $params['data'];
        $this->pagedata['total_msg'] = $aData['total'];
        $this->pagination($nPage,$params['page'],'track');
        $this->pagedata['controller'] = "inbox";
        $this->output();
    }

    function view_msg(){
        $nMsgId = $_POST['comment_id'];
        $objMsg = kernel::single('b2c_message_msg');
        $aMsg = $objMsg->getList('comment',array('comment_id' => $nMsgId,'for_comment_id' => 'all','to_id'=>$this->app->member_id));
        if($aMsg[0]&&($aMsg[0]['author_id']!=$this->app->member_id&&$aMsg[0]['to_id']!=$this->app->member_id)){
            header('Content-Type:text/html; charset=utf-8');
            echo app::get('b2c')->_('对不起，您没有权限查看这条信息！');exit;
        }
        $objMsg->setReaded($nMsgId);
        $objAjax = kernel::single('b2c_view_ajax');
        echo $objAjax->get_html(htmlspecialchars_decode($aMsg[0]['comment']),'b2c_ctl_site_member','view_msg');
        exit;

    }

    function deleteMsg() {
        if(!empty($_POST['delete'])){
            $objMsg = kernel::single('b2c_message_msg');
            if($objMsg->check_msg($_POST['delete'],$this->app->member_id)){
                $objMsg->delete(array('object_type' => 'msg','comment_id' =>$_POST['delete']));
                $this->splash('success','reload',app::get('b2c')->_('删除成功'),$_POST['response_json']);
            }else{
                $this->splash('failed',null,app::get('b2c')->_('参数提交错误'),$_POST['response_json']);
            }
        }else{
            $this->splash('failed',null,app::get('b2c')->_('没有选中任何记录'),$_POST['response_json']);
        }
    }

    function send($nMsgId=false,$type='') {
        $this->get_msg_num();
        if($nMsgId){
            $objMsg = kernel::single('b2c_message_msg');
            $init =  $objMsg->dump($nMsgId);
            if($type == 'reply'){
                $objMsg->setReaded($nMsgId);
                $init['to_uname'] = $init['author'];
                $init['subject'] = "Re:".$init['title'];
                $init['comment'] = '';
                $this->pagedata['is_reply'] = true;
            }
            else{
                $init['subject'] = $init['title'];
            }
            $this->pagedata['init'] = $init;
            $this->pagedata['comment_id'] = $nMsgId;
        }
        $this->pagedata['controller'] = "inbox";
        $this->output();
    }

    function message($nMsgId=false, $status='send') { //给管理员发信件
        $this->get_msg_num();
        if($nMsgId){
            $objMsg = kernel::single('b2c_message_msg');
            $init =  $objMsg->dump($nMsgId);
            if($init['author_id'] == $this->app->member_id)
            {
                $this->pagedata['init'] = $init;
                $this->pagedata['msg_id'] = $nMsgId;
            }
        }
        if($status === 'reply'){
            $this->pagedata['reply'] = 1;
        }
        $this->pagedata['controller'] = "inbox";
        $this->output();
    }

    /*
     *发送站内信
     * */
    function send_msg(){
        if(!isset($_POST['msg_to']) || $_POST['msg_to'] == '管理员'){
            $_POST['to_type'] = 'admin';
            $_POST['msg_to'] = 0;
        }else{
            $userObject = kernel::single('b2c_user_object');
            $to_id = $userObject->get_id_by_uname($_POST['msg_to']);
            if(!$to_id){
                $this->splash('failed',null,app::get('b2c')->_('收件人不存在'),$_POST['response_json']);
            }
            $_POST['to_id'] = $to_id;
        }
        if($_POST['subject'] && $_POST['comment']) {
            $objMessage = kernel::single('b2c_message_msg');
            $_POST['has_sent'] = $_POST['has_sent'] == 'false' ? 'false' : 'true';
            $_POST['member_id'] = $this->app->member_id;
            $_POST['uname'] = $this->member['uname'];
            $_POST['contact'] = $this->member['email'];
            $_POST['ip'] = $_SERVER["REMOTE_ADDR"];
            $_POST['subject'] = strip_tags($_POST['subject']);
            $_POST['comment'] = strip_tags($_POST['comment']);
            if($_POST['comment_id']){
                //$data['comment_id'] = $_POST['comment_id'];
                $_POST['comment_id'] = '';//防止用户修改comment_id
            }
            if( $objMessage->send($_POST) ) {
                if($_POST['has_sent'] == 'false'){
                    $this->splash('success','reload',app::get('b2c')->_('保存到草稿箱成功'),$_POST['response_json']);
                }else{
                    $this->splash('success','reload',app::get('b2c')->_('发送成功'),$_POST['response_json']);
                }
            } else {
                $this->splash('failed',null,app::get('b2c')->_('发送失败'),$_POST['response_json']);
            }
        }
        else {
            $this->splash('failed',null,app::get('b2c')->_('必填项不能为空'),$_POST['response_json']);
        }
    }

    /*
     *会员中心 修改密码页面
     * */
    function security($type = ''){
        $member = $this->member;
        $obj_pam_members = app::get('pam')->model('members');
        $this->pagedata['is_nopassword'] = $obj_pam_members->is_nopassword($member['member_id']);
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('修改密码'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $this->output();
    }

    /*
     *保存修改密码
     * */
    function save_security(){
        $member = $this->member;
        $obj_pam_members = app::get('pam')->model('members');
        $passport_login = $this->gen_url(array('app'=>'b2c','ctl'=>'site_passport','act'=>'login'));
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_passport','act'=>'logout','arg0'=>$passport_login));
        $userPassport = kernel::single('b2c_user_passport');
        if($obj_pam_members->is_nopassword($member['member_id']) == 'true')
        {
            $result = $userPassport->reset_passport($this->app->member_id,$_POST['passwd']);
            if($result)
            {
                $this->splash('success',null,app::get('b2c')->_('修改成功'),true);
            }else{
                $this->splash('failed',null,app::get('b2c')->_('修改失败'),true);
            }
        }
        $result = $userPassport->save_security($this->app->member_id,$_POST,$msg);
        if($result){
            $this->splash('success',$url,$msg,true);
        }else{
            $this->splash('failed',null,$msg,true);
        }
    }

    /*
     *会员中心收货地址
     * */
    function receiver(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('收货地址'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $objMem = $this->app->model('members');
        //添加时--收货地址处先显示默认注册的地址
        $adds = $objMem->getRow('area,addr',array('member_id'=>$this->app->member_id));
        if($adds){
            $this->pagedata['dizhi'] = $adds;
        }

        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['receiver'] = $objMem->getMemberAddr($this->app->member_id);
        $this->pagedata['is_allow'] = (count($this->pagedata['receiver'])<10 ? 1 : 0);
        $this->pagedata['num'] = count($this->pagedata['receiver']);
        $this->pagedata['res_url'] = $this->app->res_url;
        $this->output();
    }


    /*
     * 设置和取消默认地址，$disabled 2为设置默认1为取消默认
     */
    function set_default($addrId=null,$disabled=2){
        // $addrId = $_POST['addr_id'];
        if(!$addrId) $this->splash('failed',null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'receiver'));
        $obj_member = $this->app->model('members');
        $member_id = $this->app->member_id;
        //------liuyulei------
        if($addrId && $member_id) {
            $member_addr = $this->app->model('member_addrs');
            $row = $member_addr->getList('addr_id,area,addr', array('addr_id' => $addrId, 'member_id' => $member_id));
            if($row){
                if($obj_member->set_to_def($addrId,$member_id,$message,$disabled)){
                    $message =  json_encode($row[0],true);
                    $this->splash('success',$url,$message,true);
                }else{
                    $this->splash('error',null,$message,true);
                }
            }
        }else{
            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
        }
        //------liuyulei end------
//        if($obj_member->check_addr($addrId,$member_id)){
//            if($obj_member->set_to_def($addrId,$member_id,$message,$disabled)){
//                $this->splash('success',$url,$message,true);
//            }else{
//                $this->splash('error',null,$message,true);
//            }
//        }else{
//            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
//        }
    }

    /*
     *添加、修改收货地址
     * */
    function modify_receiver($addrId=null){
        // $addrId = $_POST['addr_id'];
        if(!$addrId){
            echo  app::get('b2c')->_("参数错误");exit;
        }
        $obj_member = $this->app->model('members');

        if($obj_member->check_addr($addrId,$this->app->member_id)){
            if($aRet = $obj_member->getAddrById($addrId)){
                $aRet['defOpt'] = array('0'=>app::get('b2c')->_('否'), '1'=>app::get('b2c')->_('是'));
                $this->pagedata['dizhi'] = $aRet;
            }else{
                echo  app::get('b2c')->_("修改的收货地址不存在");exit;
            }

            echo $this->fetch('site/member/modify_receiver.html');exit;
        }else{
            echo  app::get('b2c')->_("参数错误");exit;
        }
    }

    /*
     *保存收货地址
     * */
    function save_rec(){
        if($_POST['check']&&$_POST['check']=='check_out'){
            $save_data = kernel::single('b2c_member_addrs')->purchase_save_addr($_POST,$this->app->member_id,$msg);
            if(!$save_data){
                $this->splash('error',null,$msg,true);
            }
            $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),app::get('b2c')->_('保存成功'),true);
        }else{
            if(!$_POST['def_addr']){
                $_POST['def_addr'] = 0;
            }
            $save_data = kernel::single('b2c_member_addrs')->purchase_save_addr($_POST,$this->app->member_id,$msg);
            if(!$save_data){
                $this->splash('error',null,$msg,true);
            }
            $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'receiver')),app::get('b2c')->_('保存成功'),true);
        }
    }

    /*
     *删除收货地址
     * */
    function del_rec($addrId=null){
        // $addrId = $_POST['addr_id'];
        if(!$addrId) $this->splash('failed', null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'receiver'));
        $obj_member = $this->app->model('members');
        if($obj_member->check_addr($addrId,$this->app->member_id)){
            if($obj_member->del_rec($addrId,$message,$this->app->member_id)){
                $this->splash('success',$url,$message,true);
            }else{
                $this->splash('failed',$url,$message,true);
            }
        }else{
            $this->splash('failed',$url, app::get('b2c')->_('参数错误'),true);
        }
    }

    function exchange($cpnsId=null) {
        //积分设置的用途
        $site_point_usage = app::get('b2c')->getConf('site.point_usage');
        if($site_point_usage != '1'){
            $this->splash('failed',$url,app::get('b2c')->_('积分只用于抵扣，不能兑换'),true);
        }
        if(!$cpnsId) $this->splash('failed',$url, app::get('b2c')->_('参数错误'),true);
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        $memberId = intval($this->app->member_id);//会员id号
        if($memberId){
            $membersData = $this->get_current_member();
            $cur_coupon_nums = $this->app->model('member_coupon')->count(array('cpns_id'=>$cpnsId,'member_id'=>$memberId));
            $coupons = $this->app->model('coupons');
            $cur_coupon = $coupons->dump($cpnsId);
            if($cur_coupon['cpns_max_num'] > 0 ){  //兼容老数据处理老数据还是无限制兑换
                if($cur_coupon_nums >= $cur_coupon['cpns_max_num']){
                    $this->splash('failed',$url,app::get('b2c')->_('您的兑换次数已达上限！'),true);
                }
            }
            if($membersData['point'] < $cur_coupon['cpns_point']){
                $this->splash('failed',$url,app::get('b2c')->_('您的积分不足！'),true);
            }
            if ($oExchangeCoupon->exchange($cpnsId,$memberId,$membersData['point'],$params)){
                $cpns_point = $params['cpns_point'];
                $member_point = $this->app->model('member_point');
                if($member_point->change_point($this->member['member_id'],-$cpns_point,$msg,'exchange_coupon',2,$memberId,$memberId,'exchange')){
                    $change_nums = $cur_coupon['cpns_max_num'] - $cur_coupon_nums -1;
                    $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'coupon'));
                    if($cur_coupon['cpns_max_num'] > 0 ){
                        $this->splash('success',$url,app::get('b2c')->_('兑换成功,您还可以兑换'.$change_nums.'张'),true);
                    }
                    else{
                        $this->splash('success',$url,app::get('b2c')->_('兑换成功'),true);
                    }
                }else{
                    $oExchangeCoupon->exchange_delete($params);
                    $this->splash('failed',$url,$msg,array('request'=>true));
                }
            }
        }else{
            $this->splash('failed',$url,app::get('b2c')->_('没有登录'),true);
        }
        $this->splash('failed',$url,app::get('b2c')->_('积分不足或兑换购物券无效'),true);
    }

    function download_ddvanceLog(){
        $charset = kernel::single('base_charset');
        $obj_member = $this->app->model('member_advance');
        $aData = $obj_member->get_list_bymemId($this->app->member_id);
        header('Pragma: no-cache, no-store');
        header("Expires: Wed, 26 Feb 1997 08:21:57 GMT");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=advance_".date("Ymd").".csv");
        $out = app::get('b2c')->_("事件,存入金额,支出金额,当前余额,时间\n");
        foreach($aData as $v){
            $out .= $v['message'].",".$v['import_money'].",".$v['explode_money'].",".$v['member_advance'].",".date("Y-m-d H:i",$v['mtime'])."\n";
        }
        echo $charset->utf2local($out,'zh');
        exit;
    }

    /**
     * 添加留言
     * @params string order_id
     * @params string message type
     */
    public function addMsgData(){
        $timeHours = array();
        for($i=0;$i<24;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeHours[$v] = $v;
        }
        $timeMins = array();
        for($i=0;$i<60;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeMins[$v] = $v;
        }
        $this->pagedata['orderId'] = $order_id;
        $this->pagedata['msgType'] = $msgType;
        $this->pagedata['timeHours'] = $timeHours;
        $this->pagedata['timeMins'] = $timeMins;

        $this->output();
    }

    /**
     * 订单留言提交
     * @params null
     * @return null
     */
    public function toadd_order_msg()
    {
        if(!$_POST['msg']['orderid']){
            $this->splash(false,app::get('b2c')->_('参数错误'),true);
        }
        $this->begin(array('app'=>'b2c','ctl'=>'site_member','act'=>'orderdetail','arg0'=>$_POST['msg']['orderid']));
        $obj_filter = kernel::single('b2c_site_filter');
        $_POST = $obj_filter->check_input($_POST);

        $_POST['to_type'] = 'admin';
        $_POST['author_id'] = $this->app->member_id;
        $_POST['author'] = $this->member['uname'];
        $is_save = true;
        $obj_order_message = kernel::single("b2c_order_message");
        if ($obj_order_message->create($_POST))
            $this->end(true,app::get('b2c')->_('留言成功'),null,false,true);
        else
            $this->end(false,app::get('b2c')->_('留言失败'),null,false,true);
    }

    /*
        过滤POST来的数据,基于安全考虑,会把POST数组中带HTML标签的字符过滤掉
    */
    function check_input($data){
        $aData = $this->arrContentReplace($data);
        return $aData;
    }

    function arrContentReplace($array){
        if (is_array($array)){
            foreach($array as $key=>$v){
                $array[$key] =     $this->arrContentReplace($array[$key]);
            }
        }
        else{
            $array = strip_tags($array);
        }
        return $array;
    }

    function set_read($comment_id=null,$object_type='ask'){
        if(!$comment_id) return ;
        $comment = kernel::single('b2c_message_disask');
        $comment->type = $object_type;
        $reply_data = $comment->getList('comment_id',array('for_comment_id' => $comment_id));
        foreach($reply_data as $v){
            $comment->setReaded($v['comment_id']);
        }

    }


    /*
     * 获取评论咨询的数据
     *
     * */
    public function getComment($nPage=1,$type='discuss'){
        //获取评论咨询基本数据
        $comment = kernel::single('b2c_message_disask');
        $aData = $comment->get_member_disask($this->app->member_id,$nPage,$type,$this->pagesize);
        $gids = array();
        $productGids = array();
        $comment_ids = array();
        foreach((array)$aData['data'] as $k => $v){
            $comment_ids[] = $v['comment_id'];
            if($v['type_id'] && !in_array($v['type_id'],$gids) ){
                $gids[] = $v['type_id'];
            }
            if(!$v['product_id'] && !in_array($v['type_id'],$productGids) ){
                $productGids[] = $v['type_id'];
            }

            if($v['items']){//统计回复未读的数量
                $unReadNum = 0;
                foreach($v['items'] as $val){
                    if($val['mem_read_status'] == 'false' ){
                        $unReadNum += 1;
                    }
                }
            }
            $aData['data'][$k]['unReadNum'] = $unReadNum;
        }

        //获取货品ID
        $productData = $productGids ? $this->app->model('products')->getList('goods_id,product_id',array('goods_id'=>$productGids,'is_default'=>'true')) : array();
        foreach((array) $productData as $p_row){
            $productList[$p_row['goods_id']] = $p_row['product_id'];
        }
        $this->pagedata['productList'] = $productList;

        //评论咨询商品信息
        $goodsData = $gids ? $this->app->model('goods')->getList('goods_id,name,price,thumbnail_pic,udfimg,image_default_id',array('goods_id'=>$gids)) : null;
        if($goodsData){
            foreach($goodsData as $row){
                $goodsList[$row['goods_id']] = $row;
            }
        }
        $this->pagedata['goodsList'] = $goodsList;

        //评论咨询私有的数据
        if($type == 'discuss'){
            $this->pagedata['point_status'] = app::get('b2c')->getConf('goods.point.status') ? app::get('b2c')->getConf('goods.point.status'): 'on';
            if($this->pagedata['point_status'] == 'on'){//如果开启评分则获取评论评分
                $objPoint = $this->app->model('comment_goods_point');
                $goods_point = $objPoint->get_comment_point_arr($comment_ids);
                $this->pagedata['goods_point'] = $goods_point;
            }
        }else{
            $gask_type = unserialize($this->app->getConf('gask_type'));//咨询类型
            foreach((array)$gask_type as $row){
                $gask_type_list[$row['type_id']] = $row['name'];
            }
            $this->pagedata['gask_type'] = $gask_type_list;
        }
        return $aData;
    }

    function comment($nPage=1){
        if($this->app->getConf('comment.switch.discuss') == 'off'){
            kernel::single('site_router')->http_status(404);return;
        }
        //面包屑
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('评论与咨询'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $comment = $this->getComment($nPage,'discuss');
        $this->pagedata['commentList'] = $comment['data'];
        $this->pagination($nPage,$comment['page'],'comment');
        $this->output();
    }

    function ask($nPage=1){
        if($this->app->getConf('comment.switch.ask') == 'off'){
            kernel::single('site_router')->http_status(404);return;
        }
        //面包屑
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('评论与咨询'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $this->pagedata['controller'] = "comment";
        $comment = $this->getComment($nPage,'ask');
        $this->pagedata['commentList'] = $comment['data'];
        $this->pagedata['commentType'] = 'ask';
        $this->pagination($nPage,$comment['page'],'ask');
        $this->action_view = 'comment.html';
        $this->output();
    }

    /*
     *未评论商品
     **/
    public function nodiscuss($nPage=1){
        if($this->app->getConf('comment.switch.discuss') == 'off'){
            kernel::single('site_router')->http_status(404);return;
        }
        //面包屑
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('未评论商品'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        //获取会员已发货的商品日志
        $sell_logs = $this->app->model('sell_logs')->getList('order_id,product_id,goods_id',array('member_id'=>$this->app->member_id));
        //获取会员已评论的商品
        $comments = $this->app->model('member_comments')->getList('order_id,product_id',array('author_id'=>$this->app->member_id,'object_type'=>'discuss','for_comment_id'=>'0'));
        $data = array();
        if($comments){
            foreach((array)$comments as $row){
                if($row['order_id'] && $row['product_id']){
                    $data[$row['order_id']][$row['product_id']] = $row['product_id'];
                }
            }
        }

        foreach((array)$sell_logs as $key=>$log_row){
            if($data && $data[$log_row['order_id']][$log_row['product_id']] == $log_row['product_id']){
                unset($sell_logs[$key]);
            }else{
                $filter['order_id'][] = $log_row['order_id'];
                $filter['product_id'][] = $log_row['product_id'];
                $filter['item_type|noequal'] = 'gift';
            }
        }

        $orderItemModel = app::get('b2c')->model('order_items');
        $limit = $this->pagesize;
        $start = ($nPage-1)*$limit;
        $i = 0;
        $nogift = $orderItemModel->getList('order_id,product_id',$filter);
        if($nogift){
            foreach($nogift as $row){
                $tmp_nogift_order_id[] = $row['order_id'];
                $tmp_nogift_product_id[] = $row['product_id'];
            }
        }
        foreach((array)$sell_logs as $key=>$log_row){
            if(in_array($log_row['order_id'],$tmp_nogift_order_id) && in_array($log_row['product_id'],$tmp_nogift_product_id) ){//剔除赠品,赠品不需要评论
                if($i >= $start && $i < ($nPage*$limit) ){
                    $sell_logs_data[] = $log_row;
                    $gids[] = $log_row['goods_id'];
                }
                if($nogift){
                    $i += 1;
                }
            }
        }
        $totalPage = ceil($i/$limit);
        if($nPage > $totalPage) $nPage = $totalPage;

        $this->pagedata['list'] = $sell_logs_data;
        $this->pagination($nPage,$totalPage,'nodiscuss');

        if($gids){
            //获取商品信息
            $goodsData = $this->app->model('goods')->getList('goods_id,name,image_default_id',array('goods_id'=>$gids));
            $goodsList = array();
            foreach((array)$goodsData as $goods_row){
                $goodsList[$goods_row['goods_id']]['name'] = $goods_row['name'];
                $goodsList[$goods_row['goods_id']]['image_default_id'] = $goods_row['image_default_id'];
            }
            $this->pagedata['goods'] = $goodsList;

            $this->pagedata['point_status'] = app::get('b2c')->getConf('goods.point.status') ? app::get('b2c')->getConf('goods.point.status'): 'on';
            $this->pagedata['verifyCode'] = $this->app->getConf('comment.verifyCode');
            if($this->pagedata['point_status'] == 'on'){
                //评分类型
                $comment_goods_type = $this->app->model('comment_goods_type');
                $this->pagedata['comment_goods_type'] = $comment_goods_type->getList('*');
                if(!$this->pagedata['comment_goods_type']){
                    $sdf['type_id'] = 1;
                    $sdf['name'] = app::get('b2c')->_('商品评分');
                    $addon['is_total_point'] = 'on';
                    $sdf['addon'] = serialize($addon);
                    $comment_goods_type->insert($sdf);
                    $this->pagedata['comment_goods_type'] = $comment_goods_type->getList('*');
                }
            }

            $this->pagedata['submit_comment_notice'] = $this->app->getConf('comment.submit_comment_notice.discuss');
        }
        $this->output();
    }

    ##缺货登记
    function notify($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('到货通知'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $membersData = kernel::single('b2c_user_object')->get_members_data(array('members'=>'member_lv_id'));
        $oMem = $this->app->model('member_goods');
        $aData = $oMem->get_gnotify($this->app->member_id,$membersData['members']['member_lv_id'],$nPage);
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['notify'] = $aData['data'];
        $this->pagination($nPage,$aData['page'],'notify');
        $setting['buytarget'] = $this->app->getConf('site.buy.target');
        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $this->pagedata['setting'] = $setting;
        $this->pagedata['member_id'] = $this->app->member_id;
        $this->output();
    }

    ##删除缺货登记
    function del_notify($pid=null){
        $member_id = $this->app->member_id;
        if(!$pid || !$member_id) $this->splash('failed', 'back', app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'notify'));
        $member_goods= $this->app->model('member_goods');
        if($member_goods->getList('gnotify_id',array('product_id' => $pid,'member_id' => $this->app->member_id))){
            if($member_goods->delete(array('product_id'=>$pid,'member_id'=>$this->app->member_id))){
                $this->splash('success',$url,app::get('b2c')->_('移除成功'),true);
            }else{
                $this->splash('failed',null,app::get('b2c')->_('没有选中任何记录'),true);
            }
        }else{
            $this->splash('failed',null,app::get('b2c')->_('没有选中任何记录'),true);
        }

    }

    function coupon($nPage=1) {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('我的优惠券'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $oCoupon = kernel::single('b2c_coupon_mem');
        $aData = $oCoupon->get_list_m($this->app->member_id,$nPage);
        if ($aData) {
            foreach ($aData as $k => $item) {
                if ($item['coupons_info']['cpns_status'] !=1) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('此种优惠券已取消');
                    continue;
                }

                $member_lvs = explode(',',$item['time']['member_lv_ids']);
                if (!in_array($this->member['member_lv'],(array)$member_lvs)) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('本级别不准使用');
                    continue;
                }

                $curTime = time();
                if ($curTime>=$item['time']['from_time'] && $curTime<$item['time']['to_time']) {
                    if ($item['memc_used_times']<$this->app->getConf('coupon.mc.use_times')){
                        if ($item['coupons_info']['cpns_status']){
                            $aData[$k]['memc_status'] = app::get('b2c')->_('可使用');
                        }else{
                            $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券已作废');
                        }
                    }else{
                        $aData[$k]['coupons_info']['cpns_status'] = false;
                        $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券次数已用完');
                    }
                }else{
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('还未开始或已过期');
                }
            }
        }

        $total = $oCoupon->get_list_m($this->app->member_id);
        $this->pagination($nPage,ceil(count($total)/$this->pagesize),'coupon');
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['coupons'] = $aData;
        $this->output();
    }

    /*
     * 积分兑换优惠卷
     * */
    function couponExchange($page=1) {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('积分兑换优惠卷'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $pageLimit = $this->pagesize;
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        $filter = array('ifvalid'=>1);
        $site_point_usage = $this->app->getConf('site.point_usage');
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['site_point_usage'] = ($site_get_policy_method != '1' && $site_point_usage == '1') ? 'true' : 'false';
        if ($aExchange = $oExchangeCoupon->get_list()) {
            foreach ($aExchange as $k => $item) {
                $member_lvs = explode(',',$item['time']['member_lv_ids']);
                if (!in_array($this->member['member_lv'],(array)$member_lvs)) {
                    unset($aExchange[$k]);
                    continue;
                }
            }
            $this->pagedata['couponList'] = $aExchange;
        }
        $this->output();
    }

    /**
    /*
     * 重新购买
     * @param  int  $order_id [description]
     * @param  boolean $archive  [description]
     */
    public function reAddCart($order_id,$archive=false){
        $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_cart','arg'=>$order_id));
        if(!$order_id){
            $this->splash('error',$url);
        }
        $orderItemObj = $archive ? app::get('b2c')->model('archive_order_items') : app::get('b2c')->model('order_items');
        $ordersData = $orderItemObj->getList('*',array('order_id'=>$order_id));
        foreach($ordersData as $row){
            $product_id[] = $row['product_id'];
            if($row['item_type'] == 'product'){
                $cartData[$row['obj_id']]['goods']['goods_id'] = $row['goods_id'];
                $cartData[$row['obj_id']]['goods']['product_id'] = $row['product_id'];
                //修改再次购买加入购物车数量，与原订单商品数量保持一致----jyy
                $cartData[$row['obj_id']]['goods']['num'] = $row['nums'];
                $cartData[$row['obj_id']][0] = 'goods';
                $cartData[$row['obj_id']]['order_id'] = $order_id;
            }elseif($row['item_type'] == 'adjunct'){
                $cartData[$row['obj_id']]['goods']['adjunct'][0][$row['product_id']] = 1;
            }
        }
        //预售商品进入再次购买的判断
        $prepare=kernel::service('prepare_goods');
        if($prepare)
        {
            $pre=$prepare->get_product_buyagain($product_id);

            foreach ($pre as $key => $value) {
                $prep[] = $value['promotion_type'];
            }
            //echo '<pre>';print_r($prep);exit();
            if (!empty($prep))
            {
                $msg = app::get('b2c')->_('预售商品不能加入购物车！');
                if(in_array('prepare', $prep)){
                    $this->splash('error',$url,$msg);
                }
            }
        }
        $obj_cart_object = kernel::single('b2c_cart_objects');
        $obj_goods = kernel::single('b2c_cart_object_goods');
        foreach($cartData as $goods){
            $obj_ident = $obj_cart_object->add_object($obj_goods, $goods, $msg);
        }

        $this->splash('error',$url);

    }

    public function securitycenter(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('安全中心'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $member_id = $this->app->member_id;
        $pamMemberData = app::get('pam')->model('members')->getList('*',array('member_id'=>$member_id));
        foreach($pamMemberData as $row){
            if($row['login_type'] == 'mobile' && $row['disabled'] == 'false'){
                $data['mobile'] = $row['login_account'];
                $data['phone_setting'] = $row['phone_setting'];
                $verify['mobile'] = true;
            }

            if($row['login_type'] == 'email' && $row['disabled'] == 'false'){
                $data['email'] = $row['login_account'];
                $verify['email'] = true;
            }
        }
        $this->pagedata['data'] = $data;
        $this->pagedata['verify'] = $verify;
        $this->output();
    }

    function verify($verifyType='verifymobile') {
        unset($_SESSION['vcodeVerifykey']['activation']);
        $member_id = $this->app->member_id;
        $pamMemberData = app::get('pam')->model('members')->getList('*',array('member_id'=>$member_id));
        foreach($pamMemberData as $row){
            if($row['login_type'] == 'mobile' && $row['disabled'] == 'false'){
                $data['mobile'] = $row['login_account'];
                $data['phone_setting'] = $row['phone_setting'];
                $verify['mobile'] = true;
            }

            if($row['login_type'] == 'email' && $row['disabled'] == 'false'){
                $data['email'] = $row['login_account'];
                $verify['email'] = true;
            }
        }
        $this->pagedata['site_sms_valide'] = $this->app->getConf('site.sms_valide');
        $this->pagedata['verifyType'] = $verifyType;
        $this->pagedata['verify'] = $verify;
        $this->pagedata['data'] = $data;
        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;
        $this->output();
    }

    public function verify_vcode(){
        $send_type = $_POST['send_type'];
        if( isset($_POST['password']) ){
            $pamMembersModel = app::get('pam')->model('members');
            $pamData = $pamMembersModel->getList('login_password,password_account,createtime',array('member_id'=>$this->app->member_id));
            $use_pass_data['login_name'] = $pamData[0]['password_account'];
            $use_pass_data['createtime'] = $pamData[0]['createtime'];
            $login_password = pam_encrypt::get_encrypted_password(trim($_POST['password']),'member',$use_pass_data);
            if($login_password !== $pamData[0]['login_password']){
                $msg=app::get('b2c')->_('登录密码错误');
                $this->splash('failed',null,$msg,true);exit;
            }else{
                $_SESSION['vcodeVerifykey']['activation'] = 'true';
                $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'verify2','arg0'=>$_POST['verifyType']));
                $this->splash('success',$url);
            }
        }

        $userVcode = kernel::single('b2c_user_vcode');
        if( !$userVcode->verify($_POST['vcode'][$send_type],$_POST[$send_type],'activation')){
            $msg = app::get('b2c')->_('验证码错误');
            $this->splash('failed',null,$msg,true);exit;
        }

        $_SESSION['vcodeVerifykey']['activation'] = 'true';
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'verify2','arg0'=>$_POST['verifyType']));
        $this->splash('success',$url);
    }

    function verify2($verifyType){
        if( !$_SESSION['vcodeVerifykey']['activation'] ){
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'verify','arg0'=>$verifyType));
            $this->redirect($url);
        }

        $userPassport = kernel::single('b2c_user_passport');
        $member_id = $userPassport->userObject->get_member_id();
        $arr_colunms = $userPassport->userObject->get_pam_data('login_account',$member_id);
        $this->pagedata['site_sms_valide'] = $this->app->getConf('site.sms_valide');
        $this->pagedata['verifyType'] = $verifyType;
        $this->pagedata['data'] = $arr_colunms;
        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;
        $this->output();
    }

    function verify_vcode2($verifyType){
        unset($_SESSION['vcodeVerifykey']['activation']);
        $send_type = $_POST['send_type'];
        $userVcode = kernel::single('b2c_user_vcode');
        if( !$userVcode->verify($_POST['vcode'],$_POST['uname'],$send_type)){
            $msg = app::get('b2c')->_('验证码错误');
            $this->splash('failed',null,$msg,true);exit;
        }

        $userPassport = kernel::single('b2c_user_passport');
        $accountType = $userPassport->get_login_account_type($_POST['uname']);
        if($_POST['send_type'] == 'reset'){
            if( !$userPassport->set_new_account($this->app->member_id,trim($_POST['uname']),$msg,trim($_POST['phone_setting'])) ){
                $msg = $msg ? $msg : app::get('b2c')->_('修改信息失败');
                $this->splash('failed',null,$msg,true);exit;
            }
        }else{
            if( !app::get('pam')->model('members')->update(array('login_account'=>$_POST['uname'],'disabled'=>'false'),array('member_id'=>$this->app->member_id,'login_type'=>$accountType)) ){
                $msg = app::get('b2c')->_('重置信息失败');
                $this->splash('failed',null,$msg,true);exit;
            }
        }
        //增加会员同步 2012-05-15
        if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
            $member_rpc_object->modifyActive($this->app->member_id);
        }
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'verify3','arg0'=>$verifyType));
        $this->splash('success',$url);
    }

    function verify3($verifyType){
        $this->pagedata['verifyType'] = $verifyType;
        $this->output();
    }

    function cancel($order_id){
        $this->pagedata['cancel_order_id'] = $order_id;
        $this->page('site/member/order_cancel_reason.html');

    }

    function docancel(){
        $arrMember = kernel::single('b2c_user_object')->get_current_member(); //member_id,uname
        //开启事务处理
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();

        $order_cancel_reason = $_POST['order_cancel_reason'];
        if($order_cancel_reason['reason_type'] == 7 && !$order_cancel_reason['reason_desc'])
        {
            $msg = app::get('b2c')->_('请输入详细原因');
            $this->splash('error','',$msg,true);
        }
        if(strlen($order_cancel_reason['reason_desc'])>150)
        {
            $msg = app::get('b2c')->_('详细原因过长，请输入50个字以内');
            $this->splash('error','',$msg,true);
        }
        if($order_cancel_reason['reason_type'] != 7 && strlen($order_cancel_reason['reason_desc']) > 0)
        {
            $order_cancel_reason['reason_desc'] = '';
        }
        $order_cancel_reason = utils::_filter_input($order_cancel_reason);
        $order_cancel_reason['cancel_time'] = time();
        $mdl_order = app::get('b2c')->model('orders');
        $sdf_order_member_id = $mdl_order->getRow('member_id', array('order_id'=>$order_cancel_reason['order_id']));
        if($sdf_order_member_id['member_id'] != $arrMember['member_id'])
        {
            $db->rollback();
            $msg = app::get('b2c')->_('请勿取消别人的订单');
            $this->splash('error','',$msg,true);
            return;
        }

        $mdl_order_cancel_reason = app::get('b2c')->model('order_cancel_reason');
        $result = $mdl_order_cancel_reason->save($order_cancel_reason);
        if(!$result)
        {
            $db->rollback();
            $msg = app::get('b2c')->_('订单取消原因记录失败');
            $this->splash('error','',$msg,true);
        }
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if (!$obj_checkorder->check_order_cancel($order_cancel_reason['order_id'],'',$message))
        {
            $db->rollback();
            $this->splash('error','',$message,true);
        }

        $sdf['order_id'] = $order_cancel_reason['order_id'];
        $sdf['op_id'] = $arrMember['member_id'];
        $sdf['opname'] = $arrMember['uname'];
        $sdf['account_type'] = 'member';

        $b2c_order_cancel = kernel::single("b2c_order_cancel");
        if ($b2c_order_cancel->generate($sdf, $this, $message))
        {
            if($order_object = kernel::service('b2c_order_rpc_async')){
                $order_object->modifyActive($sdf['order_id']);
            }
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index'));
            $db->commit($transaction_status);
            $msg = app::get('b2c')->_('订单取消成功');
            $this->splash('success',$url,$msg,true);
        }
        else
        {
            $db->rollback();
            $msg = app::get('b2c')->_('订单取消失败');
            $this->splash('error','',$msg,true);
        }
    }

    /*******收货人相关 edit by kim********/
    /**
     *  收货人信息维护
     **/
    function consignee(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('收货人信息'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $objMem = $this->app->model('members');
        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;

        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['cons'] = $objMem->getMemberCons($this->app->member_id);
        $this->pagedata['is_allow'] = (count($this->pagedata['cons'])<6 ? 1 : 0);
        $this->pagedata['num'] = count($this->pagedata['cons']);
        $this->pagedata['res_url'] = $this->app->res_url;
        $this->output();
    }

    /*
     *保存收货人
     * */
    function save_cons(){
        if(!$_POST['def_person']){
            $_POST['def_person'] = 0;
        }
        $save_data = kernel::single('b2c_member_consignee')->purchase_save_cons($_POST,$this->app->member_id,$msg);
        if(!$save_data){
            $this->splash('error',null,$msg,true);
        }
        $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'consignee')),app::get('b2c')->_('保存成功'),true);
    }

    /*
     *添加、修改收货人信息
     * */
    function modify_cons($cons_id=null){
        if(!$cons_id){
            echo  app::get('b2c')->_("参数错误");exit;
        }
        $obj_member = $this->app->model('members');
        if($obj_member->check_cons($cons_id,$this->app->member_id)){
            if($aRet = $obj_member->getConsById($cons_id)){
                $aRet['defOpt'] = array('0'=>app::get('b2c')->_('否'), '1'=>app::get('b2c')->_('是'));
                $this->pagedata = $aRet;

                //获取地区手机前缀
                $phones=app::get('b2c')->getConf('setting-phone.phone');
                $this->pagedata['phones'] = $phones;
            }else{
                echo  app::get('b2c')->_("修改的信息不存在");exit;
            }
            echo $this->fetch('site/member/modify_consignee.html');exit;
        }else{
            echo  app::get('b2c')->_("参数错误");exit;
        }
    }

    /*
     *删除收货人
     * */
    function del_cons($cons_id=null){
        if(!$cons_id) $this->splash('failed', null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'consignee'));
        $obj_member = $this->app->model('members');
        if($obj_member->check_cons($cons_id,$this->app->member_id)){
            if($obj_member->del_cons($cons_id,$message,$this->app->member_id)){
                $this->splash('success',$url,$message,true);
            }else{
                $this->splash('failed',$url,$message,true);
            }
        }else{
            $this->splash('failed',$url, app::get('b2c')->_('参数错误'),true);
        }
    }

    /*
     * 设置和取消默认收货人，$disabled 2为设置默认1为取消默认
     */
    function set_default_person($cons_id=null,$disabled=2){
        if(!$cons_id) $this->splash('failed',null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'consignee'));
        $obj_member = $this->app->model('members');
        $member_id = $this->app->member_id;
        //------liuyulei------
        if($cons_id && $member_id) {
            $member_cons = $this->app->model('member_consignee');
            $row = $member_cons->getList('consignee_id,name,tel,mobile,phone_setting',array('consignee_id' => $cons_id, 'member_id' => $member_id));
            if($row){
                if($obj_member->set_to_defp($cons_id,$member_id,$message,$disabled)){
                    $message =  json_encode($row[0],true);
                    $this->splash('success',$url,$message,true);
                }else{
                    $this->splash('error',null,$message,true);
                }
            }
        }else{
            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
        }
        //------liuyulei end------
//        if($obj_member->check_cons($cons_id,$member_id)){
//            if($obj_member->set_to_defp($cons_id,$member_id,$message,$disabled)){
//                $this->splash('success',$url,$message,true);
//            }else{
//                $this->splash('error',null,$message,true);
//            }
//        }else{
//            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
//        }
    }

    /*******收货公司相关 edit by kim********/
    function company(){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('付款公司'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;

        $objMem = $this->app->model('members');
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagedata['coms'] = $objMem->getMemberComs($this->app->member_id);
        $this->pagedata['is_allow'] = (count($this->pagedata['coms'])<6 ? 1 : 0);
        $this->pagedata['num'] = count($this->pagedata['coms']);
        $this->pagedata['res_url'] = $this->app->res_url;

        //默认地区
        $aMemInfo=$objMem->dump($this->app->member_id,'*');
        $this->pagedata['area'] = $aMemInfo['area'];

        $this->pagedata['default'] = '1';
        $this->output();
    }

    /*
     *保存付款公司
     * */
    function save_company(){
        if(!$_POST['def_company']){
            $_POST['def_company'] = 0;
        }

        if($_POST['c_type'] == '3'){
            //验证手机格式
            $phone_setting = $_POST['phone_setting'];
            $phones = app::get('b2c')->getConf('setting-phone.phone');
            foreach($phones as $v){
                $bool  = in_array($phone_setting,$v);
                if($bool){
                    $len = $v['length'];
                    break;
                }
            }

            if((!preg_match('/^[1-9]\d{'.($len-1).'}$/', $_POST['tel']))){
                $this->splash('error', null, app::get('b2c')->_('手机格式错误'),true);
            }
        }

        $save_data = kernel::single('b2c_member_company')->purchase_save_company($_POST,$this->app->member_id,$msg);
        if(!$save_data){
            $this->splash('error',null,$msg,true);
        }

        $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'company')),app::get('b2c')->_('保存成功'),true);
    }

    /*
     *删除付款公司
     * */
    function del_coms($company_id=null){
        if(!$company_id) $this->splash('failed', null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'company'));
        $obj_member = $this->app->model('members');
        if($obj_member->check_coms($company_id,$this->app->member_id)){
            if($obj_member->del_coms($company_id,$message,$this->app->member_id)){
                $this->splash('success',$url,$message,true);
            }else{
                $this->splash('failed',$url,$message,true);
            }
        }else{
            $this->splash('failed',$url, app::get('b2c')->_('参数错误'),true);
        }
    }

    /*
     *添加、修改付款公司信息
     * */
    function modify_coms($company_id=null){
        if(!$company_id){
            echo  app::get('b2c')->_("参数错误");exit;
        }
        $obj_member = $this->app->model('members');
        if($obj_member->check_coms($company_id,$this->app->member_id)){
            if($aRet = $obj_member->getComsById($company_id)){
                $aRet['defOpt'] = array('0'=>app::get('b2c')->_('否'), '1'=>app::get('b2c')->_('是'));
                $this->pagedata = $aRet;

                //获取地区手机前缀
                $phones=app::get('b2c')->getConf('setting-phone.phone');
                $this->pagedata['phones'] = $phones;
            }else{
                echo  app::get('b2c')->_("修改的信息不存在");exit;
            }
            echo $this->fetch('site/member/modify_company.html');exit;
        }else{
            echo  app::get('b2c')->_("参数错误");exit;
        }
    }

    /*
     * 设置和取消默认付款公司，$disabled 2为设置默认1为取消默认
     */
    function set_default_company($company_id=null,$disabled=2){
        if(!$company_id) $this->splash('failed',null, app::get('b2c')->_('参数错误'),true);
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'company'));
        $obj_member = $this->app->model('members');
        $member_id = $this->app->member_id;
        //------liuyulei------
        if($company_id && $member_id) {
            $member_coms = $this->app->model('member_company');
            $row = $member_coms->getList('company_id,name,inn,c_type,inn_p',array('company_id' => $company_id, 'member_id' => $member_id));
            if($row){
                if($obj_member->set_to_defc($company_id,$member_id,$message,$disabled)){
                    $message =  json_encode($row[0],true);
                    $this->splash('success',$url,$message,true);
                }else{
                    $this->splash('error',null,$message,true);
                }
            }
        }else{
            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
        }
        //------liuyulei end------
//        if($obj_member->check_coms($company_id,$member_id)){
//            if($obj_member->set_to_defc($company_id,$member_id,$message,$disabled)){
//                $this->splash('success',$url,$message,true);
//            }else{
//                $this->splash('error',null,$message,true);
//            }
//        }else{
//            $this->splash('error',null, app::get('b2c')->_('参数错误'),true);
//        }
    }

    /******************************供应商部分****************************************/
    //供应商基础信息维护---只有主账号可以维护
    function businessbaseinfo(){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('供应商信息维护'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $objMem = $this->app->model('members');
        $bbModel = $this->app->model('business_basicmsg');
        $member_id = $this->app->member_id;

        //子账号没有权限查看此页面
        if($objMem->getRow('*',array('member_id'=>$member_id,'is_main'=>2))){
            $this->splash('falied',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index')), app::get('b2c')->_('对不起，您没有修改权限'),false);
        }

        //该主账号所属的供应商
        if($objMem->check_main($member_id)){
            $business = $bbModel->getRow('*',array('member_id'=>$member_id));
        }

        //获取地区手机前缀
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        $this->pagedata['phones'] = $phones;
        $this->pagedata['business'] = $business;
        $this->output();
    }

    //供应商基本信息的修改操作
    function save_baseinfo(){
        $bbModel = $this->app->model('business_basicmsg');
        $data = $_POST['business'];
        $data['check_time'] = strtotime($data['check_time']);

        $this->check_phone($data['phone_setting1'],$data['company_tel1']);
        $this->check_phone($data['phone_setting2'],$data['company_tel2']);

        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'businessbaseinfo'));
        $bool = $bbModel->update($data,array('business_id'=>$_POST['business_id']));
        if(!$bool){
            $this->splash('failed',$url,app::get('b2c')->_('修改失败'),true);
        }
        $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'businessbaseinfo')),app::get('b2c')->_('修改成功'),true);
    }

    function check_phone($prefix,$mobile){
        //验证手机格式
        $phones=app::get('b2c')->getConf('setting-phone.phone');
        foreach($phones as $v){
            $bool  = in_array($prefix,$v);
            if($bool){
                $len = $v['length'];
                break;
            }
        }
        if((!empty($mobile) && !preg_match('/^[1-9]\d{'.($len-1).'}$/', $mobile))){
            $msg = app::get('b2c')->_('手机格式错误');
            $this->splash('failed',null,$msg,true);
        }
    }

    //正在销售的商品 edit by kim
    function preserve_product($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('在售商品 Товары в продаже'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;


        $members = $this->app->model('members');
        $business_brand = $this->app->model('business_brand');
        $brand = $this->app->model('brand');
        $business_basicmsg = $this->app->model('business_basicmsg');
        $oGoods = $this->app->model('goods');

        $member_id = $this->app->member_id;

        //取得该账户下的供应商 关联的品牌
        $bids = $members -> getRow('business_id',array('member_id'=>$member_id));
        $business_id = $bids['business_id'];

        $brands = $business_brand->getList('brand_id',array('business_id'=>$business_id));
        foreach($brands as $row){
            $newarr[] = $row['brand_id'];
        }

        if($business_id == 0){
            //主账号为0 去business_basicmsg里查
            $b_arr = $business_basicmsg->getRow('business_id',array('member_id'=>$member_id));
            $business_id = $b_arr['business_id'];
            $brands = $business_brand->getList('brand_id',array('business_id'=>$business_id));
            foreach($brands as $row){
                $newarr[] = $row['brand_id'];
            }
            $brands_name = $brand->getList('brand_id,brand_name',array('brand_id'=>$newarr));
            foreach($brands_name as $v){
                $arr['brand_name'][$v['brand_id']] = $v['brand_name'];
            }
        }else{
            //子账号直接查表
            $brands_name = $brand->getList('brand_id,brand_name',array('brand_id'=>$newarr));
            foreach($brands_name as $v){
                $arr['brand_name'][$v['brand_id']] = $v['brand_name'];
            }
        }

        //获取该品牌下的商品数据
        $goods = $oGoods->getList('*',array('business_id'=>$business_id,'marketable'=>'true','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name'],'bn|has'=>$_POST['content']['bn']));
        $count = count($goods);
        $this->pagedata['brands'] = $arr;


        //根据business_id取出商品
        $aPage = $this->get_start($nPage,$count);
//        $goodsData = $oGoods->getList('*',array('business_id'=>$business_id,'marketable'=>'true','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name']),$aPage['start'],$this->pagesize);
//        foreach($goodsData as $key=>$v){
//            $ids[] = $v['goods_id'];
//            $products = $this->app->model('products')->getRow('*',array('goods_id'=>$ids));
//            $goodsData[$key]['product']= $products;
//        }

        $goodsData = $this->app->model('goods')->batch_dump(array('business_id'=>$business_id,'marketable'=>'true','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name'],'bn|has'=>$_POST['content']['bn']),'*','account_mode',$aPage['start'],20,'bn desc');
        $goods_type_props_value = $this->app->model('goods_type_props_value');
        if(!empty($goodsData)){
            foreach($goodsData as $key=>$value){
                //季节
                $goodsData[$key]['season'] = current($goods_type_props_value->getRow('name',array('props_value_id'=>$value['props']['p_1']['value'])));
            }
        }

        $this->process_goods($goodsData);//数据处理 by yyj 2016/1/25
        $this->pagedata['goods'] = $goodsData;
        //echo '<pre>';
        //print_r($goodsData);
        //echo '</pre>';exit();
        $this->pagedata['opt'] = 'preserve_product';//操作 by yyj 2016/1/25

        if(!empty($_POST['content'])){
            $this->pagedata['brand'] = $_POST['content']['brand'];
            $this->pagedata['name'] = $_POST['content']['name'];
            $this->pagedata['bn'] = $_POST['content']['bn'];
        }
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagination($nPage,$params['page'],'preserve_product');
        $this->output();
    }

    //处理商品数据 by yyj 2016/1/25
    function process_goods(&$goods){
        foreach($goods as $key => $data){
            $products = array();
            foreach($data['product'] as $pkey => $product){
                $products[] = $product;
            }
            $goods[$key]['product'] = $products;
        }
    }


    //未上架的产品 edit by kim
    function none_product($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('下架商品 Товары не в продаже'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $members = $this->app->model('members');
        $business_brand = $this->app->model('business_brand');
        $brand = $this->app->model('brand');
        $business_basicmsg = $this->app->model('business_basicmsg');
        $oGoods = $this->app->model('goods');

        $member_id = $this->app->member_id;

        //取得该账户下的供应商 关联的品牌
        $bids = $members -> getRow('business_id',array('member_id'=>$member_id));
        $business_id = $bids['business_id'];

        $brands = $business_brand->getList('brand_id',array('business_id'=>$business_id));
        foreach($brands as $row){
            $newarr[] = $row['brand_id'];
        }

        if($business_id == 0){
            //主账号为0 去business_basicmsg里查
            $b_arr = $business_basicmsg->getRow('business_id',array('member_id'=>$member_id));
            $business_id = $b_arr['business_id'];
            $brands = $business_brand->getList('brand_id',array('business_id'=>$business_id));
            foreach($brands as $row){
                $newarr[] = $row['brand_id'];
            }
            $brands_name = $brand->getList('brand_id,brand_name',array('brand_id'=>$newarr));
            foreach($brands_name as $v){
                $arr['brand_name'][$v['brand_id']] = $v['brand_name'];
            }
        }else{
            //子账号直接查表
            $brands_name = $brand->getList('brand_id,brand_name',array('brand_id'=>$newarr));
            foreach($brands_name as $v){
                $arr['brand_name'][$v['brand_id']] = $v['brand_name'];
            }
        }

        //获取该品牌下的商品数据
        $goods = $oGoods->getList('*',array('business_id'=>$business_id,'marketable'=>'false','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name'],'bn|has'=>$_POST['content']['bn']));
        //$goodsData = $this->app->model('goods')->batch_dump(array('business_id'=>$business_id,'marketable'=>'false','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name'],'bn'=>$_POST['content']['bn']),'*','account_mode',$aPage['start'],$this->pagesize);
        //$this->pagedata['goods'] = $goodsData;
        $count = count($goods);
        $this->pagedata['brands'] = $arr;

        //根据business_id取出商品
        $aPage = $this->get_start($nPage,$count);
        //$this->pagedata['goods'] = $oGoods->getList('*',array('brand_id'=>$newarr),$aPage['start'],$this->pagesize);
        $goodsData = $this->app->model('goods')->batch_dump(array('business_id'=>$business_id,'marketable'=>'false','brand_id'=>$_POST['content']['brand'],'name'=>$_POST['content']['name'],'bn|has'=>$_POST['content']['bn']),'*','account_mode',$aPage['start'],20,'bn asc');
        $goods_type_props_value = $this->app->model('goods_type_props_value');
        if(!empty($goodsData)){
            foreach($goodsData as $key=>$value){
                //季节
                $goodsData[$key]['season'] = current($goods_type_props_value->getRow('name',array('props_value_id'=>$value['props']['p_1']['value'])));
            }
        }
        $this->process_goods($goodsData);
        $this->pagedata['goods'] = $goodsData;
        //echo '<pre>';
        //print_r($goodsData);
        //echo '</pre>';exit();
        $this->pagedata['opt'] = 'none_product';//操作 by yyj 2016/1/25
        if(!empty($_POST['content'])){
            $this->pagedata['brand'] = $_POST['content']['brand'];
            $this->pagedata['name'] = $_POST['content']['name'];
            $this->pagedata['bn'] = $_POST['content']['bn'];
        }

        $params['page'] = $aPage['maxPage'];
        $this->pagedata['browser'] = $this->get_browser();
        $this->pagination($nPage,$params['page'],'none_product');
        $this->output();
    }


    //维护商品上架操作
    function goods_onsell(){
        $gid = trim($_POST['goods_id']);
        if($gid){
            $Goods = $this->app->model('goods');
            $products = $this->app->model('products');
            //维护商品上架，将goods表中marketable上架同时将products表中的商品上架--jyy 2016/12/12--
            $goo = $Goods -> update(array('marketable'=>'true'),array('goods_id'=>$gid));
            $pro_goo = $products->update(array('marketable'=>'true'),array('goods_id'=>$gid));
            if($goo){
                $this->splash('success','reload',app::get('b2c')->_('上架成功'),$_POST['response_json']);
            }else{
                $this->splash('failed',null,app::get('b2c')->_('参数提交错误'),$_POST['response_json']);
            }
        }
    }

    //下架操作
    function goods_offsell(){
        $gid = trim($_POST['goods_id']);
        if($gid){
            $Goods = $this->app->model('goods');
            $products = $this->app->model('products');
            //维护商品下架，将goods表中marketable下架同时将products表中的商品下架--jyy 2016/12/12--
            $goo = $Goods -> update(array('marketable'=>'false'),array('goods_id'=>$gid));
            $pro_goo = $products->update(array('marketable'=>'false'),array('goods_id'=>$gid));
            if($goo){
                $this->splash('success','reload',app::get('b2c')->_('下架成功'),$_POST['response_json']);
            }else{
                $this->splash('failed',null,app::get('b2c')->_('参数提交错误'),$_POST['response_json']);
            }
        }
    }

    /*
     * 供应商对自己的商品进行批量上下架操作
     * author:jyy 2017/08/30
     */

    function batch_goods_issell()
    {
        $goods_id = $_POST['check_item'];
        $is_sell = $_POST['is_sell'];

        $Goods = $this->app->model('goods');
        $products = $this->app->model('products');
        if(!empty($goods_id) && $is_sell=='on'){
            foreach($goods_id as $key=>$value)
            {
                //维护商品下架，将goods表中marketable上架同时将products表中的商品上架
                $goods_data = $Goods -> update(array('marketable'=>'true'),array('goods_id'=>$value));
                $products_data = $products->update(array('marketable'=>'true'),array('goods_id'=>$value));
            }
            $msg = array('status'=> 'success');
            echo json_encode($msg);exit();
        }
        elseif(!empty($goods_id) && $is_sell=='off') {
            foreach($goods_id as $key=>$value){
                //维护商品下架，将goods表中marketable下架同时将products表中的商品下架
                $goods_data = $Goods -> update(array('marketable'=>'false'),array('goods_id'=>$value));
                $products_data = $products->update(array('marketable'=>'false'),array('goods_id'=>$value));
            }
            $msg = array('status'=> 'success');
            echo json_encode($msg);exit();
        }else{
            $msg = array('status'=> 'error');
            echo json_encode($msg);exit();
        }
    }

    /**
     * @param $gid
     * @param $opt
     * 供应商对该商品重新计算价格
     */
    function business_update_goods_price()
    {
        $msg='参数错误';
        if(empty($_POST['goods_id']))
        {
            echo json_encode(array('error'=>$msg));exit;
        }

        $goods_id = trim($_POST['goods_id']);

        //销售单价
        $goods_price = round($_POST['goods_price']);//四舍五入取整
        //标识
        $is_tag = $_POST['is_tag'];

        $objGoods = $this->app->model('goods');
        $objBrand = $this->app->model('brand');
        $products = $this->app->model('products');

        $goods = $objGoods->getRow('*',array('goods_id'=>$goods_id));
        $brand = $objBrand->getRow('*',array('brand_id'=>$goods['brand_id']));

        //价格计算公式：
        //编辑s_price时（account_mode为rebate）：
        //需要同时更新sdb_b2c_goods和sdb_b2c_products这两个表格里的s_price，cost，price三个字段
        //cost=s_price*(1-sdb_b2c_brand.rebate);（需要取整数）
        //price=s_price*unit_num;（需要取整数）

        //编辑cost时（account_mode为account）：
        //需要同时更新sdb_b2c_goods和sdb_b2c_products这两个表格里的cost，s_price，price三个字段
        //s_price=cost/(1-sdb_b2c_brand.rebate);（需要取整数）
        //price=s_price*unit_num;（需要取整数）
        if(!empty($goods_id) && $goods_price>0 && $is_tag == 's_price')//编辑销售单价
        {
            $cost = round($goods_price*(1-$brand['rebate']/100));//采购价
            $price = round($goods_price*intval($goods['unit_num']));//销售价
            //更新价格
            $goods_data = $objGoods -> update(array('price'=>$price,'cost'=>$cost,'s_price'=>$goods_price,'last_modify'=>time()),array('goods_id'=>$goods_id));
            $products_data = $products->update(array('price'=>$price,'cost'=>$cost,'s_price'=>$goods_price,'last_modify'=>time()),array('goods_id'=>$goods_id));
            if($goods_data && $products_data){
                $msg = array('goods_id'=>$goods_id,'s_price'=>$goods_price,'cost'=>$cost,'status'=> 'success');
                echo json_encode($msg);exit();
            }else{
                $msg = array('status'=> 'error');
                echo json_encode($msg);exit();
            }
        }
        elseif(!empty($goods_id) && $goods_price>0 && $is_tag == 'cost')//编辑采购价
        {
            $s_price = round($goods_price/(1-$brand['rebate']/100));//销售单价
            $price = round($s_price*intval($goods['unit_num']));//销售价
            //更新价格
            $goods_data = $objGoods -> update(array('price'=>$price,'cost'=>$goods_price,'s_price'=>$s_price,'last_modify'=>time()),array('goods_id'=>$goods_id));
            $products_data = $products->update(array('price'=>$price,'cost'=>$goods_price,'s_price'=>$s_price,'last_modify'=>time()),array('goods_id'=>$goods_id));
            if($goods_data && $products_data){
                $msg = array('goods_id'=>$goods_id,'s_price'=>$s_price,'cost'=>$goods_price,'status'=> 'success');
                echo json_encode($msg);exit();
            }else{
                $msg = array('status'=> 'error');
                echo json_encode($msg);exit();
            }

        }




    }





    //编辑商品信息 by kim
    function goods_edit($gid,$opt){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('编辑产品'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        //商品详细信息
        $goods = $this->app->model('goods')->dump(array('goods_id'=>$gid),'*','account_mode');

        //获取计量单位
        $unit=app::get('b2c')->getConf('goods.unit');
        foreach($unit as $key=>$value){
            $this->pagedata['unit'][$value]=$value;
        }
        $this->pagedata['goods'] = $goods;
        $this->pagedata['opt'] = $opt;//操作点 by yyj 2016/1/25
        $this->pagedata['controller'] = $opt;//控制点 by yyj 2016/1/25

        $this->output();
    }

    /*
     *对商品的修改内容进行保存操作
     * */
    function save_goods(){
//        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'preserve_product'));
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>$_POST['opt']));//操作点 by yyj 2016/1/25
        $obj_goods = $this->app->model('members');
        $goods_id = $_POST['gid'];
        $brand_id = $this->app->model('goods')->getRow('brand_id',array('goods_id'=>$goods_id));
        $bid = $brand_id['brand_id'];
        $bool = $obj_goods->insertGood($_POST,$bid);
        if($bool){
            $this->splash('success',$url,app::get('b2c')->_('修改成功'),true);
        }else{
            $this->splash('failed',$url,app::get('b2c')->_('修改失败'),true);
        }
    }

    //获取登录供应商的business_id
    private function get_bid(){
        $role = $this->pagedata["role_business"]; //登录的所属供应商
        if($role=='1'){
            $list = $this->app->model('business_basicmsg')->getRow('business_id',array('member_id'=>$this->app->member_id));
            $business_id = $list['business_id'];
        }else{
            $list = $this->app->model('members')->getRow('business_id',array('member_id'=>$this->app->member_id));
            $business_id = $list['business_id'];
        }
        return $business_id;
    }

    //已经确认库存商品
    function confirmed($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('已确认订单 Подтвержден заказ'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $business_id = $this->get_bid();
        //库存确认时间
        $confirm_start = strtotime($_POST['confirm_time']);
        $confirm_end = strtotime($_POST['confirm_time'])+24*60*60;
        $ordersObj = $this->app->model('business_orders_objects');
        if(!empty($_POST['confirm_time'])){
            //依据确认时间筛选库存商品
            $count = count($ordersObj->getList('*',array('state'=>'1','business_id'=>$business_id,'confirm_time|bthan'=>$confirm_start,'confirm_time|sthan'=>$confirm_end)));
            $aPage = $this->get_start($nPage,$count);
            $goods_list = $ordersObj->batch_dump(array('state'=>'1','business_id'=>$business_id,'confirm_time|bthan'=>$confirm_start,'confirm_time|sthan'=>$confirm_end),'*',array(':goods'=>array('*',array(':brand'=>('*')))),$aPage['start'],$this->pagesize,'confirm_time desc');
        }else{
            $count = count($ordersObj->getList('*',array('state'=>'1','business_id'=>$business_id)));
            $aPage = $this->get_start($nPage,$count);
            $goods_list = $ordersObj->batch_dump(array('state'=>'1','business_id'=>$business_id),'*',array(':goods'=>array('*',array(':brand'=>('*')))),$aPage['start'],$this->pagesize,'confirm_time desc');
        }
        //添加未确认库存商品图片信息-------jyy 2016/10/13----
        $goods_type_props_value = $this->app->model('goods_type_props_value');
        foreach($goods_list as $key => $item)
        {
            //添加图片
            $goods_list[$key]['image_default_id'] = base_storager::image_path($item['image_default_id']);
            //季节
            $goods_list[$key]['season'] = current($goods_type_props_value->getRow('name',array('props_value_id'=>$item['goods']['props']['p_1']['value'])));
        }
        //库存确认时间筛选
        if(!empty($_POST['confirm_time'])){
            $this->pagedata['confirm_time'] = $_POST['confirm_time'];
        }
        $this->pagedata['count'] = $count;
        $this->pagedata['goods'] = $goods_list;
        $this->pagedata['browser'] = $this->get_browser();
        $params['page'] = $aPage['maxPage'];
        $this->pagination($nPage,$params['page'],'confirmed');
        $this->output();
    }

    /**
     * 供应商未确认库存
     **/
    function no_inventory($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('新订单 новый заказ'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $business_id = $this->get_bid();
        $ordersObj = $this->app->model('business_orders_objects');
        $bordersObj = $this->app->model('business_orders');
        $b_ids = $bordersObj->getList('childOrder_id',array('order_status|noequal'=>'dead','business_id'=>$business_id));
        //$sql = "SELECT B.childOrder_id FROM sdb_business_orders B join sdb_b2c_business_goodscollection G on B.childOrder_id = G.childOrder_id where B.business_id = '{$business_id}' and B.order_status <> 'dead' and G.status <> '2'";
        //$b_ids = $ordersObj->db->select($sql);
        $order_ids = array();
        foreach($b_ids as $key => $id){
            $order_ids[] = $id['childOrder_id'];
        }
        $count = count($ordersObj->getList('*',array('state'=>'0','business_id'=>$business_id,'childOrder_id|in'=>$order_ids)));
        $aPage = $this->get_start($nPage,$count);
        $goods_list = $ordersObj->batch_dump(array('state'=>'0','business_id'=>$business_id,'childOrder_id|in'=>$order_ids),'*',array(':goods'=>array('*',array(':brand'=>('*')))),$aPage['start'],$this->pagesize,'createtime desc');
        $goods_list = $this->get_total_confirm_num($goods_list);
        //添加未确认库存商品图片信息-------jyy 2016/10/13----
        $goods_type_props_value = $this->app->model('goods_type_props_value');
        foreach($goods_list as $key => $item)
        {
            //添加图片
            $goods_list[$key]['image_default_id'] = base_storager::image_path($item['image_default_id']);
            //季节
            $goods_list[$key]['season'] = current($goods_type_props_value->getRow('name',array('props_value_id'=>$item['goods']['props']['p_1']['value'])));
        }
        $this->pagedata['goods'] = $goods_list;
        $this->pagedata['browser'] = $this->get_browser();
        $params['page'] = $aPage['maxPage'];
        $this->pagination($nPage,$params['page'],'no_inventory');
//		echo '<pre>';print_R($goods_list);
        $this->output();
    }

    //计算订单商品已确认未集货数量
    function get_total_confirm_num($goods_list){
        $bordersObj = $this->app->model('business_orders');
        foreach($goods_list as $key => $order){
            $sql = "SELECT sum(A.has_confirm_num - A.gc_confirm_num) AS total_confirm_num FROM sdb_b2c_business_orders_objects as A LEFT JOIN sdb_b2c_orders AS H ON H.order_id = A.mainOrder_id LEFT JOIN (select * from sdb_b2c_business_goodscollection where status <> '2') as L on A.childOrder_id = L.childOrder_id LEFT JOIN sdb_b2c_business_orders AS B ON A.childOrder_id=B.childOrder_id WHERE H.status='active' and B.order_status<>'dead' and A.state='1' and A.goods_id='".$order['goods']['goods_id']."'";
            $total_num = $bordersObj->db->select($sql);
            $goods_list[$key]['goods']['total_confirm_num'] = isset($total_num[0]['total_confirm_num'])?$total_num[0]['total_confirm_num']:0;
        }
        return $goods_list;
    }

    function to_confirm(){
        $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'no_inventory','full'=>1));
        $business_id = $this->get_bid();
        $sonOrderModel = $this->app->model('business_orders_objects');
        if($_POST['opt'] && ($_POST['opt'] == 'single')){
            $obj_id = $_POST['obj_id'];
            $confirm_num = $_POST['confirm_num'][$obj_id];
            $row = $sonOrderModel->getRow('*',array('obj_id'=>$obj_id));
            $this->update_order($row,$confirm_num,$obj_id);
            $this->check_status($row,$business_id);
            if($_POST['opt'] == 'single'){//单条库存确认
                $isConfirm = $sonOrderModel->update(array('has_confirm_num'=>$confirm_num,'confirm_num'=>$confirm_num,'state'=>'1'),array('obj_id'=>$obj_id));
                $this->do_single($row,$business_id);
            }else{//库存不足，商品下架，/
                $items = $sonOrderModel->getList('*',array('goods_id'=>$row['goods_id'],'state'=>'0'));
                foreach($items as $key => $item){
                    $isConfirm = $sonOrderModel->update(array('has_confirm_num'=>$confirm_num,'confirm_num'=>$confirm_num,'state'=>'1'),array('obj_id'=>$item['obj_id']));
                    $this->do_single($item,$item['business_id']);
                }
                $goods = $this->app->model('goods');
                $goods->update(array('marketable'=>false),array('goods_id'=>$row['goods_id']));
                $products = $this->app->model('products');
                $products->update(array('marketable'=>false),array('goods_id'=>$row['goods_id']));
            }
        }else{//批量库存确认
            if($_POST['is_checked']){
                foreach($_POST['is_checked'] as $key => $obj_id){
                    $confirm_num = $_POST['confirm_num'][$obj_id];
                    $row = $sonOrderModel->getRow('*',array('obj_id'=>$obj_id));
                    $this->update_order($row,$confirm_num,$obj_id);
                    $this->check_status($row,$business_id);
                    $isConfirm = $sonOrderModel->update(array('has_confirm_num'=>$confirm_num,'confirm_num'=>$confirm_num,'state'=>'1'),array('obj_id'=>$obj_id));
                    $this->do_single($row,$business_id);
                }
            }
        }
        $this->splash('success',$url,app::get('b2c')->_('修改成功'),true);
    }

    //确认库存后，修改订单的金额 liuyulei
    private  function update_order($row,$confirm_num,$obj_id,$marketable=0){
        $sonOrderModel = $this->app->model('business_orders_objects');
        $orderModel = $this->app->model('orders');//liuyulei 商品折扣根据确认数量重新计算
        $orderitemsModel = $this->app->model('order_items');//liuyulei 商品折扣根据确认数量重新计算
        $goodsModel = $this->app->model('goods');//liuyulei 商品
        $aGoodsnum = $goodsModel->getRow('unit_num', array('goods_id' => $row['goods_id']));
        $aGoods = $orderitemsModel->getRow('item_id,goods_price,goods_discount', array('product_id' => $row['product_id'], 'order_id' => $row['mainOrder_id']));
        $aOrder = $orderModel->getRow('pmt_goods,pmt_order,final_amount,weight', array('order_id' => $row['mainOrder_id']));
        //商品下架：同时下架goods表和product表中的marketable置为false
        $productsModel = $this->app->model('products');
        if($marketable){
            $goodsModel->update(
                array('marketable'=>'false'),
                array('goods_id'=>$row['goods_id'])
            );
            $productsModel->update(array('marketable'=>'false'),array('goods_id'=>$row['goods_id']));

            $this->admin_memo[] = '商品下架：[商品id:'.$row['goods_id'].']';
        }
        if($row['quantity'] > $confirm_num){
            if(!$marketable) {
                $goodsModel->update(
                    array('marketable' => 'false'),
                    array('goods_id' => $row['goods_id'])
                );
                //下架products表
                $productsModel->update(array('marketable'=>'false'),array('goods_id'=>$row['goods_id']));
            }

            $pmt  =  $confirm_num*($aGoods['goods_discount']/$row['quantity']);
            $amount = $confirm_num*$aGoods['goods_price'] - $pmt;
            $orderitemsModel->update(array('has_confirm_num'=>$confirm_num,'amount'=>$amount,'goods_discount'=>$pmt), array('item_id'=>$aGoods['item_id']));

            if(!$marketable) {
                $this->admin_memo[] = '商品下架：[商品id:' . $row['goods_id'] . ']';
            }
        }
        //if( $row['quantity'] > $confirm_num ) {
        //---------liuyulei 商品折扣根据确认数量重新计算----------
        //商品的优惠后（含商品活动和订单活动给的优惠）单价=原单价-商品活动优惠金额-（原单价-商品活动优惠金额）/订单商品优惠（不含订单活动优惠）后总金额*（订单活动优惠总金额）
        $dePmt = ($aGoods['goods_price'] - $aGoods['goods_discount']/$row['quantity'])
            -  ($aGoods['goods_price'] - $aGoods['goods_discount']/$row['quantity'] )
            / ($aOrder['final_amount'] + $aOrder['pmt_order'])
            * $aOrder['pmt_order'];
        $dePmt = round($dePmt);
        $sonOrderModel->update(array('order_refund' => $dePmt,'confirm_time'=>time()), array('obj_id' => $obj_id));
        $this->admin_memo[] = '商品退款金额：'
            . '[商品id:'.$row['goods_id'].']'
            . '[需确认数:'.$row['quantity'].']'
            . '[确认库存数:'.$confirm_num.']'
            . '[退回数量:'.($row['quantity'] - $confirm_num).']'
            . '[退款单价:'.$dePmt.']'
            . '[退款金额:'.$dePmt * ($row['quantity'] - $confirm_num).']';
        //}
        /*$order_refund = 0;
        if($confirm_num > 0){
            if( ($row['quantity'] - $confirm_num) > 0) {
                $order_refund = $row['quantity'] * $dePmt - $confirm_num * $dePmt;
            }else{
                $order_refund = $confirm_num * $dePmt;
            }
        }else{
            $order_refund = $confirm_num * $dePmt;
        }
        if($order_refund>0){
            if(!$order_end) {
                $sonOrderModel->update(array('order_refund' => $order_refund), array('obj_id' => $obj_id));
                //修改订单的价格和数量 orders:total_amount final_amount  weight + items ：nums，amount,weight
                $orderModel->update(
                    array(
                        'total_amount' => $aOrder['total_amount'] - $order_refund,
                        'final_amount' => $aOrder['final_amount'] - $order_refund,
                        'weight' => $aOrder['weight'] - $aGoodsnum['weight'] * $confirm_num
                    ),
                    array('order_id' => $row['mainOrder_id'])
                );
                $orderitemsModel->update(array(
                    'nums' => $confirm_num,
                    //'amount'=>$order_refund,
                    //'weight'=>$aGoodsnum['weight']*$confirm_num
                ),
                    array('item_id' => $aGoods['item_id'])
                );
                if ($row['quantity'] > $confirm_num) {
                    $goodsModel->update(
                        array('marketable' => 'false'),
                        array('goods_id' => $row['goods_id'])
                    );
                }
            }
        }
        else{
            $busOrder = $sonOrderModel->getList('obj_id', array('childOrder_id'=>$row['childOrder_id']));
            if(count($busOrder)==1){
                $orderModel->update(
                    array(
                        'status'=> 'dead',
                    ),
                    array('order_id'=>$row['mainOrder_id'])
                );
            }else{
                //修改订单的价格和数量 orders:total_amount final_amount  weight + items ：nums，amount,weight
                $orderModel->update(
                    array(
                        'total_amount'=> $aOrder['total_amount'] - $row['quantity'] * $dePmt,
                        'final_amount'=> $aOrder['final_amount'] - $row['quantity'] * $dePmt,
                        'weight'=> $aOrder['weight'] - $aGoodsnum['weight'] * $row['quantity']
                    ),
                    array('order_id'=>$row['mainOrder_id'])
                );
            }
            $goodsModel->update(
                array('marketable'=>'false'),
                array('goods_id'=>$row['goods_id'])
            );
            $orderitemsModel->update(array('nums'=>0), array('item_id'=>$aGoods['item_id']));
        }*/
        //---------liuyulei 商品折扣根据确认数量重新计算 end----------
    }

    //判断主单状态
    function check_status($row,$business_id){
        $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'no_inventory','full'=>1));
        $sonOrderModel = $this->app->model('business_orders_objects');
        $orderModel = $this->app->model('business_orders');
        $list = $orderModel->getRow('status',array('mainOrder_id'=>$row['mainOrder_id'],'business_id'=>$business_id));
        $state = $list['status'];
        if($state == '1'){
            $this->splash('failed',$url,app::get('b2c')->_('商品已确认'),true);
        }
    }

    //订单明细确认
    function do_single($row,$business_id){
        $sonOrderModel = $this->app->model('business_orders_objects');
        $orderModel = $this->app->model('business_orders');
        if($sonOrderModel->count(array('childOrder_id'=>$row['childOrder_id'])) > 1){
            $b_status = $this->check_b_orders(array('childOrder_id'=>$row['childOrder_id']));
            $orderModel->update(array('status'=>$b_status),array('childOrder_id'=>$row['childOrder_id']));
            if($b_status == 1){
                $this->udpate_order_status($row,$business_id);
            }
        }else{
            $this->udpate_order_status($row,$business_id);
        }
    }

    //更新订单状态
    function udpate_order_status($row,$business_id){
        $orderModel = $this->app->model('business_orders');
        $filter = array('childOrder_id'=>$row['childOrder_id'],'mainOrder_id'=>$row['mainOrder_id'],'business_id'=>$business_id);
        $orderModel->update(array('status'=>'1'),$filter);
        $c_status = $this->check_order(array('mainOrder_id'=>$row['mainOrder_id']));
        if($c_status == 1 || $c_status == 2){
            $this->do_order($row['mainOrder_id']);
        }else{
            $orders_mdl = $this->app->model('orders');
            $orders_mdl->update(array('c_status'=>0),array('order_id'=>$_POST['order_id']));
        }
    }

    //liuyulei 检查确认数量与购数量
    function check_item_num2($filter){
        $objOrder = $this->app->model('business_orders_objects');
        $order_items = $objOrder->getList('*',$filter);
        $order_refund = 0;
        $has_confirm_num = 0;
        $has_confirm_status = 0;
        $cost_item =0;
        foreach($order_items as $key => $item){
            if($item['state'] == 0){
                $has_confirm_status += 1 ;
            }
            if ($item['has_confirm_num'] != $item['quantity']) {
                $order_refund += ($item['quantity'] - $item['has_confirm_num']) * $item['order_refund'];
            }
            $has_confirm_num += $item['has_confirm_num'];
        }
        $orderModel = $this->app->model('orders');
        if($has_confirm_num>0){
            if($has_confirm_status==0) {
                $aOrder = $orderModel->getRow('total_amount,final_amount,cost_freight', array('order_id' => $filter['mainOrder_id']));
                //修改订单的价格和数量 orders:total_amount final_amount
                $aOrder1 = app::get('b2c')->model('order_items')->getList('*',array('order_id'=>$filter['mainOrder_id']));

                foreach($aOrder1 as $value){
                    $cost_item +=  $value['amount'];
                }

                $pmt_order = $cost_item  - ( $aOrder['total_amount'] - $order_refund);
                $orderModel->update(
                    array(
                        'total_amount' => $aOrder['total_amount'] - $order_refund + $aOrder['cost_freight'],
                        'final_amount' => $aOrder['final_amount'] - $order_refund + $aOrder['cost_freight'],
                        'cost_item'    => $cost_item,
                        'pmt_order'    => $pmt_order,
                        'score_g'      => round(($aOrder['total_amount'] - $order_refund + $aOrder['cost_freight'])/100)
                    ),
                    array('order_id' => $filter['mainOrder_id'])
                );
                $this->admin_memo[] = '订单更新：[订单id:'.$filter['mainOrder_id'].'][订单原价:'.$aOrder['final_amount'].'][订单退款额:'.$order_refund.']';
                //供应商库存确认后要给客户发送短信,添加订单总金额，总件数，付款公司---jyy---2016/10/19
                $orders = $orderModel->getRow('*', array('order_id' => $filter['mainOrder_id']));

                //$obj_account=$this->app->model('member_account');
                $fire_data = array('order_id'=>$filter['mainOrder_id'],
                    'total_amount'=>round($orders['total_amount']),//订单总金额
                    'pay_account'=>$orders['company_name']);//付款公司
                $orderModel->fireEvent('storeconfirmpart',$fire_data,$orders['member_id']);
            }
        }else{
            $orderModel->update(
                array(
                    'status'=> 'dead',
                ),
                array('order_id'=>$filter['mainOrder_id'])
            );
            $borderModel = $this->app->model('business_orders');
            $border = $borderModel->getList(
                'childOrder_id',
                array('mainOrder_id'=>$filter['mainOrder_id'])
            );
            foreach($border as $_bok=>$_bov) {
                $borderModel->update(
                    array(
                        'order_status' => 'dead',
                    ),
                    array('childOrder_id' => $_bov['childOrder_id'])
                );
            }
            //库存确认订单全部无货，该订单作废，该订单金额改为0---jyy 2016/12/8
            $orderModel->update(
                array(
                    'total_amount' => 0,
                    'final_amount' => 0,
                    'cost_item'    => 0,
                    'pmt_order'    => 0,
                    'score_g'      => 0
                ),
                array('order_id' => $filter['mainOrder_id'])
            );

            $this->admin_memo[] = '订单作废：[订单id:'.$filter['mainOrder_id'].']';
            //供应商库存确认后要给客户发送短信,添加订单总金额，总件数，付款公司---jyy---2016/10/19
            $orders = $orderModel->getRow('*', array('order_id' => $filter['mainOrder_id']));
            //$obj_account=$this->app->model('member_account');
            $fire_data = array('order_id'=>$filter['mainOrder_id']);
            $orderModel->fireEvent('storeconfirmno',$fire_data,$orders['member_id']);
        }
        //写入操作日志
        if(!empty($this->admin_memo)){
            $this->logs(implode('<br/>',$this->admin_memo));
            unset($this->admin_memo);
            $this->admin_memo = '';
        }
    }

    //供应商确认后更新主订单
    function do_order($order_id){
        $orders_mdl = $this->app->model('orders');
        $orders_ship = $orders_mdl->getRow('*',array('order_id'=>$order_id));
        $obj_type = app::get('b2c')->model('dlytype');
        $dt_info = $obj_type->dump($orders_ship['shipping_id']);
        //-----liuyulei 主订单全部确认完成，更新主单库存确认时间-----
        $sonOrderModel = $this->app->model('business_orders_objects');
        $has_finish = $sonOrderModel->getRow('obj_id',array('mainOrder_id'=>$order_id,'state'=>0));
        if(!$has_finish){
            $confirm_time = time();
        }else{
            $confirm_time = '';
            //-----liuyulei 主订单全部确认完成，更新主单库存确认时间 end-----
            //是否有推荐商品或者确认数量与购数量不同
        }
        $orders_rg_mdl = $this->app->model('business_recommend_goods');
        if($orders_rg_mdl->count(array('mainOrder_id'=>$order_id)) || $this->check_item_num(array('mainOrder_id'=>$order_id))){
            if($dt_info['cost_confirm'] == 'true'){//运费需要确认
                $c_status = '1';//待确认运费
            }else{
                $c_status = '2';//待付款
            }
            $orders_mdl->update(array('c_status'=>$c_status,'confirm_time'=>$confirm_time),array('order_id'=>$order_id));
            //---------liuyulei 订单价格修改（0个确认【订单废弃】和差集确认）-----------
            $this->check_item_num2( array('mainOrder_id'=>$order_id) );
        }else{
            if($dt_info['cost_confirm'] == 'true'){//运费需要确认
                $c_status = '1';//待确认运费
            }else{
                $c_status = '2';//待付款
            }
            $orders_mdl->update(array('c_status'=>$c_status,'confirm_time'=>$confirm_time),array('order_id'=>$order_id));
            //供应商库存确认后要给客户发送短信,添加订单总金额，总件数，付款公司---jyy---2016/10/19
            $orders = $orders_mdl->dump(array('order_id'=>$order_id),'*');

            //$obj_account=$this->app->model('member_account');
            $fire_data = array('order_id'=>$order_id,
                'total_amount'=>round($orders['total_amount']),//订单总金额
                'pay_account'=>$orders['company_name']);//付款公司
            $orders_mdl->fireEvent('storeconfirmall',$fire_data,$orders['member_id']);
        }

    }

    //检验供应商订单明细状态
    function check_b_orders($filter){
        $obj_goods = $this->app->model('business_orders_objects');
        $goods = $obj_goods->getList('*',$filter);
        $status = '0';
        $flg = true;
        foreach($goods as $key => $item){
            if($item['state'] == '1'){
                $status = '2';
            }
            if($item['state'] == '0'){
                $flg = false;
            }
        }
        if($flg){
            $status = '1';
        }
        return $status;
    }

    //检验订单下供应商订单状态
    function check_order($filter){
        $obj_goods = $this->app->model('business_orders_objects');
        $goods = $obj_goods->getList('*',$filter);
        $status = '0';
        $flg = true;
        foreach($goods as $key => $item){
            if($item['state'] == '0'){
                $flg = false;
                break;
            }
        }
        if($flg){
            $status = '1';
            $obj_order = $this->app->model('orders');
            $orders = $obj_order->getRow('*',array('order_id'=>$filter['mainOrder_id']));
            $obj_type = $this->app->model('dlytype');
            $dt_info = $obj_type->dump($orders['shipping_id']);
            if($dt_info['cost_confirm'] == 'false'){
                $status = '2';
            }
            if($orders['styke'] == 'Самовывоз' || $orders['styke'] == '自提')
            {
                $status = '2';
            }
        }

        return $status;
    }

    //检查确认数量与购数量
    function check_item_num($filter){
        $objOrder = $this->app->model('business_orders_objects');
        $order_items = $objOrder->getList('*',$filter);
        foreach($order_items as $key => $item){
            if($item['has_confirm_num'] != $item['quantity']){
                $result = true;
                break;
            }
        }
        return $result;
    }

    //确认库存中的推荐订单
    function recommend($obj_id){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('推荐商品'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $objOrder = $this->app->model('business_orders_objects');
        $goodsMdl = $this->app->model('goods');
        $productsMdl = $this->app->model('products');
        $brandMdl = $this->app->model('brand');
        $row = $objOrder->getRow('*',array('obj_id'=>$obj_id));
        $recommend_goods = $goodsMdl->getList('*',array('goods_id|noequal'=>$row['goods_id'],'business_id'=>$row['business_id'],'marketable'=>'true'));
        foreach($recommend_goods as $key => $goods){
            $recommend_goods[$key]['products'] = $productsMdl->getList('*',array('goods_id'=>$goods['goods_id'],'marketable'=>'true'));
            $recommend_goods[$key]['brand'] = $brandMdl->getRow('*',array('brand_id'=>$goods['brand_id']));
        }
        $this->pagedata['recommend_goods'] = $recommend_goods;
        $this->pagedata['obj_id'] = $obj_id;
        $this->pagedata['controller'] = "no_inventory";
        $this->output();
    }

    function do_recommend(){
        $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'no_inventory','full'=>1));
        if(!$_POST['is_selected']){
            $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'wap_member', 'act'=>'recommend','arg'=>$_POST['obj_id']));
            $this->splash('failed',$url,app::get('b2c')->_("请选择推荐商品"),true);
        }
        $objOrder = $this->app->model('business_orders_objects');
        $row = $objOrder->getRow('*',array('obj_id'=>$_POST['obj_id']));
        $this->save_recommend($row,$_POST['is_selected']);
        $isConfirm = $objOrder->update(array('has_confirm_num'=>'0','confirm_num'=>'0','state'=>'1'),array('obj_id'=>$_POST['obj_id']));
        $this->do_single($row,$row['business_id']);
        $this->splash('success',$url,app::get('b2c')->_("推荐成功"),true);
    }

    //生成推荐商品
    function save_recommend($row,$r_goods_id){
        $objRg = $this->app->model('business_recommend_goods');
        $sData['childOrder_id'] = $row['childOrder_id'];
        $sData['mainOrder_id'] = $row['mainOrder_id'];
        $sData['business_id'] = $row['business_id'];
        $sData['goods_id'] = $row['goods_id'];
        $sData['r_goods_id'] = $r_goods_id;
        $objRg->save($sData);
    }

    //会员中心，会员确认订单
    function confirm($mainOrder_id=null){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('订单确认'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $list = $this->app->model('business_orders')->getList('childOrder_id',array('mainOrder_id'=>$mainOrder_id));
        foreach($list as $v){
            $ids[] = $v['childOrder_id'];
        }
        $list = $this->app->model('business_orders_objects')->batch_dump(array('childOrder_id'=>$ids,'state'=>'1'),'*',array(':goods'=>array('*')));
        $list = $this->get_glink_info($list);
        $this->pagedata['has_rg'] = $list['has_rg'];
        unset($list['has_rg']);
        $this->pagedata['list'] = $list;
        $this->pagedata['order_id'] = $mainOrder_id;
        $this->pagedata['controller'] = "orders";
//		echo '<pre>';print_r($list);
        $this->output();
    }

    //推荐商品信息
    function get_glink_info(&$list){
        $obj_rg = app::get('b2c')->model('business_recommend_goods');
        $obj_goods = app::get('b2c')->model('goods');
        $obj_products = app::get('b2c')->model('products');
        foreach($list as $key => $item){
            $filter = array('mainOrder_id'=>$item['mainOrder_id'],'childOrder_id'=>$item['childOrder_id'],'business_id'=>$item['business_id'],'goods_id'=>$item['goods_id']);
            $r_goods = $obj_rg->getRow('*',$filter);
            if($r_goods['r_goods_id']){
                $has_rg = true;
                $list[$key]['goods']['glink'] = $r_goods;
                $list[$key]['goods']['glink']['goods'] = $obj_goods->getRow('*',array('goods_id'=>$r_goods['r_goods_id'],'marketable'=>'true'));
                $list[$key]['goods']['glink']['goods']['products'] = $obj_products->getList('*',array('goods_id'=>$r_goods['r_goods_id'],'marketable'=>'true'));
            }
        }
        $list['has_rg'] = $has_rg;
        return $list;
    }

    //删除下单商品 by yyj 2015/9/11
    function remove_goods($id=null){
        if(!$id) $this->splash('failed', null, app::get('b2c')->_('参数错误'),true);
        $sonOrderModel = $this->app->model('business_orders_objects');
        $bOrderModel = $this->app->model('business_orders');
        $row = $sonOrderModel->getRow('*',array('obj_id'=>$id));
        $sonOrderModel->delete(array('obj_id'=>$id));
        $orderItemModel = $this->app->model('order_items');
        $orderItemModel->delete(array('order_id'=>$row['mainOrder_id'],'goods_id'=>$row['goods_id']));
        if(!$sonOrderModel->getList('*',array('mainOrder_id'=>$row['mainOrder_id'],'childOrder_id'=>$row['childOrder_id']))){
            $bOrderModel->delete(array('mainOrder_id'=>$row['mainOrder_id'],'childOrder_id'=>$row['childOrder_id'],'business_id'=>$row['business_id']));
        }

        $this->update_business_order($row['mainOrder_id']);
        $obj_order_update = kernel::single('b2c_order_update');
        $filter = array('mainOrder_id'=>$row['mainOrder_id']);
        $obj_order_update->update_confirm_order($filter,$row['mainOrder_id'],'false');

        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'confirm'));
        $this->splash('success',$url,null,true);
    }

    //用户确认后修正订单 by yyj 2015/9/11
    function do_confirm_stock_again(){
        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index'));
        $obj_order = $this->app->model('orders');
        //推荐商品入单
        if($this->member_confirm_order($_POST)){
            $filter = array('obj_id|in'=>$_POST['item'],'mainOrder_id'=>$_POST['order_id']);

            //用户库存确认后生成最终订单统计
            $obj_order_update = kernel::single('b2c_order_update');
            $obj_order_update->update_confirm_order($filter,$_POST['order_id']);
        }else{
            //取消订单
            $db = kernel::database();
            $transaction_status = $db->beginTransaction();
            $b2c_order_cancel = kernel::single("b2c_order_cancel");
            $sdf['order_id'] = $_POST['order_id'];
            if ($b2c_order_cancel->generate($sdf, $this, $message)){
                if($order_object = kernel::service('b2c_order_rpc_async')){
                    $order_object->modifyActive($sdf['order_id']);
                }
                $obj_order->update(array('c_status'=>'1'),array('order_id'=>$sdf['order_id']));
                $db->commit($transaction_status);
//                $this->splash('success',$url,"订单取消成功",true);
            }
        }
        $this->redirect($url);
    }

    //处理推荐商品 by yyj 2015/11/19
    function member_confirm_order($param){
        $arr_remove_obj = array();
        $arr_remove_goods = array();
        $obj_business_order_item = $this->app->model('business_orders_objects');
        $obj_order_item = $this->app->model('order_items');
        $aData = $obj_business_order_item->getList('*',array('mainOrder_id'=>$param['order_id']));
        foreach ((array)$aData as $item){
            if (!in_array($item['obj_id'],$param['item'])){
                $arr_remove_obj[] = $item['obj_id'];
                $arr_remove_goods[] = $item['goods_id'];
            }
        }
        if( !empty($arr_remove_obj)){
            foreach($arr_remove_obj as $_arr_remove_obj)
                $test = $obj_business_order_item->delete(array('obj_id'=>$_arr_remove_obj));
            foreach($arr_remove_goods as $_arr_remove_goods)
                $test = $obj_order_item->delete(array('goods_id'=>$_arr_remove_goods,'order_id'=>$param['order_id']));
        }
        //用户确认后推荐商品处理
        $oData = $obj_business_order_item->getList('*',array('obj_id|in'=>$param['item'],'mainOrder_id'=>$param['order_id']));
        $obj_recommend_goods = $this->app->model('business_recommend_goods');
        $obj_goods = $this->app->model('goods');
        $obj_products = $this->app->model('products');

        $member_confirm_nums = 0;
        foreach($aData as $key => $item){
            $row = $obj_recommend_goods->getRow('*',array('mainOrder_id'=>$item['mainOrder_id'],'childOrder_id'=>$item['childOrder_id'],'business_id'=>$item['business_id'],'goods_id'=>$item['goods_id']));
            if($row && $param['rg_status'][$row['r_goods_id']] == '0'){//是否使用推荐
                $member_confirm_nums += $item['quantity'];
            }else{
                $member_confirm_nums += ($item['has_confirm_num'] != $item['quantity']) ? $item['has_confirm_num'] : $item['quantity'];
            }
        }

        if($member_confirm_nums == 0){
            //订单取消
            return false;
        }

        foreach($aData as $key => $item){
            $row = $obj_recommend_goods->getRow('*',array('mainOrder_id'=>$item['mainOrder_id'],'childOrder_id'=>$item['childOrder_id'],'business_id'=>$item['business_id'],'goods_id'=>$item['goods_id']));
            if($row && $param['rg_status'][$row['r_goods_id']] == '0'){//是否使用推荐
                $r_gooods = $obj_goods->getRow('*',array('business_id'=>$row['business_id'],'goods_id'=>$row['r_goods_id'],'marketable'=>'true'));
                $r_products = $obj_products->getRow('*',array('goods_id'=>$row['r_goods_id'],'marketable'=>'true'));
                if($r_gooods){
                    $business_save = array(
                        'goods_id'=>$r_gooods['goods_id'],
                        'bn'=>$r_gooods['bn'],
                        'name'=>$r_gooods['name'],
                        'price'=>$r_gooods['price'],
                        'buy_price'=>$r_gooods['price'],
                        'amount'=>$r_gooods['price']*$item['quantity'],
                        'confirm_num'=>$item['quantity'],
                        'has_confirm_num'=>$item['quantity'],
                        'image_default_id'=>$r_gooods['image_default_id'],
                    );
                    $item_save = array(
                        'prodcut_id'=>$r_products['product_id'],
                        'goods_id'=>$r_gooods['goods_id'],
                        'type_id'=>$r_gooods['type_id'],
                        'bn'=>$r_gooods['bn'],
                        'name'=>$r_gooods['name'],
                        'cost'=>$r_gooods['cost'],
                        'price'=>$r_gooods['price'],
                        'g_price'=>$r_gooods['price'],
                        'amount'=>$r_gooods['price']*$item['quantity'],
                        'nums'=>$item['quantity'],
                        'weight'=>$r_products['weight'],
                        'addon'=>'',
                    );
                    $obj_order_item->update($item_save,array('goods_id'=>$row['goods_id'],'order_id'=>$param['order_id']));
                    $obj_business_order_item->update($business_save,array('obj_id'=>$item['obj_id']));
                }
            }else{
                if($item['has_confirm_num'] != $item['quantity']){
                    $amount = $item['has_confirm_num']*$item['buy_price'];
                    $obj_order_item->update(array('nums'=>$item['has_confirm_num'],'amount'=>$amount),array('goods_id'=>$item['goods_id'],'order_id'=>$param['order_id']));
                    $obj_business_order_item->update(array('amount'=>$amount),array('obj_id'=>$item['obj_id']));
                }
            }

        }
        //供应商订单重新生成 by yyj 2015/11/19
        $this->update_business_order($param['order_id']);
        return true;
    }

    //供应商订单重新生成 by yyj 2015/11/19
    function update_business_order($order_id){
        $obj_business_order = $this->app->model('business_orders');
        $obj_business_order_item = $this->app->model('business_orders_objects');
        $obj_recommend_goods = $this->app->model('business_recommend_goods');
        $b_orders = $obj_business_order->getList('*',array('mainOrder_id'=>$order_id));
        foreach($b_orders as $key => $b_order){
            $filter = array('mainOrder_id'=>$b_order['mainOrder_id'],'childOrder_id'=>$b_order['childOrder_id'],'business_id'=>$b_order['business_id']);
            $order_items = $obj_business_order_item->getList('*',$filter);
            $order_amount = 0;
            $order_num = 0;
            foreach($order_items as $key => $item){
                $row = $obj_recommend_goods->getRow('*',array('mainOrder_id'=>$item['mainOrder_id'],'childOrder_id'=>$item['childOrder_id'],'business_id'=>$item['business_id'],'r_goods_id'=>$item['goods_id']));
                if($row){
//                    $order_amount += $item['buy_price'] * $item['quantity'];
//                    $order_num += $item['quantity'];
//                }else{
                    $order_amount += $item['buy_price'] * $item['has_confirm_num'];
                    $order_num += $item['has_confirm_num'];
                }
            }
            $obj_business_order->update(array('order_amount'=>$order_amount,'order_num'=>$order_num),$filter);
        }
    }

    //供应商分配集货员 by kim
    public function choice_operator(){
        $this->path[] = array('title'=>app::get('b2c')->_('供应商中心 Личный кабинет - Поставщик'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('集货员管理'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $membersObj = $this->app->model('members');
        $businessObj = $this->app->model('business_basicmsg');
        $boObj = $this->app->model('business_operator');
        $list = $membersObj->getList('member_id',array('user_type'=>2));
        $this->pagedata['list'] = $list;

        $member_id = $this->app->member_id;
        if($this->pagedata['is_personal']==1 && $this->pagedata['role_business'] == 1){
            $Arr=$businessObj->getRow('business_id',array('member_id'=>$member_id));
            $business_id = $Arr['business_id'];
        }elseif($this->pagedata['is_personal']==1 && $this->pagedata['role_business'] == 0){
            $Brr = $membersObj->getRow('business_id',array('member_id'=>$member_id));
            $business_id = $Brr['business_id'];
        }else{
            $business_id = 0;
        }

        $ids = $boObj->getList('operator_id',array('business_id'=>$business_id));
        foreach($ids as $v){
            $new[] = $v['operator_id'];
        }
        $this->pagedata['business_id'] = $business_id;
        $this->pagedata['new'] = $new;
        $this->output();
    }

    public function save_operator(){
        $bid = $_POST["business_id"];
        $oid = $_POST["operator_id"];

        $lists = $this->app->model('business_operator')->getList('*',array('business_id'=>$bid));
        if($lists){
            $this->app->model('business_operator')->delete(array('business_id'=>$bid));
        }

        foreach($oid as $v){
            $data['operator_id'] = $v;
            $data["business_id"] = $bid;
            $this->app->model('business_operator')->insert($data);
        }

        $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'choice_operator')),app::get('b2c')->_('保存成功'),true);
    }

    /*
     *获取集货单数量
     * */
    function get_collect_order_num($ids){
        $oMsg = app::get('b2c')->model('business_goodscollection');
        $order_ids = $this->get_bo_ids($ids);
        $row = $oMsg->getList('*',array('business_id|in' => $ids,'status' => '2'));
        $this->pagedata['confirmed_num'] = count($row)?count($row):0;
        $row = $oMsg->getList('*',array('business_id|in' => $ids,'status|noequal' => '2','childOrder_id|in'=>$order_ids));
        $this->pagedata['unconfirmed_num'] = count($row)?count($row):0;
        $row = $oMsg->getList('*',array('business_id|in' => $ids,'status' => '0','childOrder_id|in'=>$order_ids));
        $this->pagedata['tbc_num'] = count($row)?count($row):0;
        $row = $oMsg->getList('*',array('business_id|in' => $ids,'status' => '1','childOrder_id|in'=>$order_ids));
        $this->pagedata['bc_num'] = count($row)?count($row):0;
    }

    /*
     *获取当前用户所有关联的供应商ID by yyj 2015/10/20
     * */
    function get_business_ids(){
        $bo = app::get('b2c')->model('business_operator');
        $ids = $bo->getList('business_id',array('operator_id' => $this->app->member_id));
        $b_ids = array();
        foreach($ids as $key => $id){
            $b_ids[$key] = $id['business_id'];
        }
        return $b_ids;
    }

    //获取有效订单号 by yyj 2016/4/22
    public function get_bo_ids($ids){
        $b_order = $this->app->model('business_orders');
        $ids = $b_order->getList('childOrder_id',array('order_status|noequal'=>'dead','status|noequal'=>'0','business_id|in' => $ids));
        $order_ids = array();
        foreach($ids as $key => $id){
            $order_ids[] = $id['childOrder_id'];
        }
        return $order_ids;
    }

    //集货员中心--集货单(全部)
    function collect_order($nPage=1){
        $b_ids = $this->get_business_ids();
        $this->get_collect_order_num($b_ids);

        $oMsg = app::get('b2c')->model('business_goodscollection');
        $row = $oMsg->getList('*',array('business_id|in' => $b_ids));
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('business_id|in' => $b_ids),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['goodscollection'] = $params['data'];
        $this->pagedata['total_num'] = $count;
        $this->pagination($nPage,$params['page'],'collect_order');

        $this->output();
    }

    //集货员中心--集货单(待确认) 2015/10/11
    function collect_unconfirmed($nPage=1) {
        $b_ids = $this->get_business_ids();
        $this->get_collect_order_num($b_ids);

        $order_ids = $this->get_bo_ids($b_ids);
        $oMsg = app::get('b2c')->model('business_goodscollection');
        $row = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '0','childOrder_id|in'=>$order_ids));
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '0','childOrder_id|in'=>$order_ids),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['goodscollection'] = $params['data'];
        $this->pagedata['total_num'] = $count;
        $this->pagination($nPage,$params['page'],'collect_unconfirmed');
        $this->pagedata['controller'] = "collect_order";

        $this->output();
    }

    //集货员中心--集货单(部分确认) 2015/10/11
    function collect_batch_confirmed($nPage=1) {
        $b_ids = $this->get_business_ids();
        $this->get_collect_order_num($b_ids);

        $order_ids = $this->get_bo_ids($b_ids);
        $oMsg = app::get('b2c')->model('business_goodscollection');
        $row = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '1','childOrder_id|in'=>$order_ids));
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '1','childOrder_id|in'=>$order_ids),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['goodscollection'] = $params['data'];
        $this->pagedata['total_num'] = $count;
        $this->pagination($nPage,$params['page'],'collect_batch_confirmed');
        $this->pagedata['controller'] = "collect_order";

        $this->output();
    }

    //集货员中心--集货单(已确认) 2015/10/11
    function collect_confirmed($nPage=1) {
        $b_ids = $this->get_business_ids();
        $this->get_collect_order_num($b_ids);

        $oMsg = app::get('b2c')->model('business_goodscollection');
        $row = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '2'));
        $count = count($row);
        $aPage = $this->get_start($nPage,$count);
        $params['data'] = $oMsg->getList('*',array('business_id|in' => $b_ids,'status' => '2'),$aPage['start'],$this->pagesize);
        $params['page'] = $aPage['maxPage'];
        $this->pagedata['goodscollection'] = $params['data'];
        $this->pagedata['total_num'] = $count;
        $this->pagination($nPage,$params['page'],'collect_confirmed');
        $this->pagedata['controller'] = "collect_order";

        $this->output();
    }

    //集货员中心--集货单详情 2015/10/11
    function goodscollection_edit($gc_id,$switch){
        $filter['gc_id'] = $gc_id;

        $oMsg = $this->app->model('business_goodscollection');
        $row = $oMsg->getRow('*',$filter);
        $this->pagedata = array_merge_recursive($this->_editor2(array('mainOrder_id'=>$row['mainOrder_id'],'gc_id'=>$gc_id,'status'=>$row['status']), $page), $this->pagedata);
        $this->output();
    }

    //集货员中心--单个确认集货单商品库存 2015/10/12
    function do_sgc_edit($id,$goods_id){
        $sonOrderModel = $this->app->model('business_orders_objects');
        $obj_order_items = app::get('b2c')->model('order_items');
        $cData = $sonOrderModel->getRow('*',array('obj_id'=>$id));
        if($_POST['con_num'] > $cData['has_confirm_num']){
            echo '{error:"'.app::get('b2c')->_('实际集货数量不大于计划数量').'",_:null,data:null,reload:null}';
        }
        $isConfirm = $sonOrderModel->update(array('gc_confirm_num'=>$_POST['con_num']),array('obj_id'=>$id));
        $res_order_item = $obj_order_items->update(array('gcnum'=>$_POST['con_num']),array('goods_id'=>$goods_id,'order_id'=>$_POST['mainOrder_id']));
//        $status = $this->check_gc(array('mainOrder_id'=>$_POST['mainOrder_id']));
        $obj_collect = $this->app->model('business_goodscollection');
        $obj_collect->update(array('member_id'=>$this->app->member_id,'status'=>'1'),array('mainOrder_id'=>$_POST['mainOrder_id']));

//        if($status == '2'){
//            $order = $this->app->model('orders');
//            $order->update(array('c_status'=>'3'),array('order_id'=>$_POST['mainOrder_id']));
//        }

        $this->pagedata = array_merge_recursive($this->_editor2(array('mainOrder_id'=>$_POST['mainOrder_id'],'status'=>$status), $page), $this->pagedata);
        $str_html = $this->fetch('site/member/gc_list.html','b2c');
        echo '{success:"'.app::get('b2c')->_('操作成功！').'",_:null,data:"'.addslashes(str_replace("\r\n","",$str_html)).'",reload:null}';
    }

    //集货员中心--批量确认集货单商品库存 2015/10/12
    function do_goodscollection_edit(){
        $db = kernel::database();
        $db->beginTransaction();
        $obj_ids = $_POST['item'];
        $con_nums = $_POST['con_num'];
        $goods_id = $_POST['goods_id'];
        foreach($obj_ids as $key => $id){
            $sonOrderModel = $this->app->model('business_orders_objects');
            $obj_order_items = app::get('b2c')->model('order_items');
            $cData = $sonOrderModel->getRow('*',array('obj_id'=>$id));
            if($con_nums[$id] < 0){
                echo '{error:"'.app::get('b2c')->_('实际集货数量不能小于0').'",_:null,data:null,reload:null}';exit;
            }
            if($con_nums[$id] > $cData['has_confirm_num']){
                echo '{error:"'.app::get('b2c')->_('实际集货数量不大于计划数量').'",_:null,data:null,reload:null}';exit;
            }
            $isConfirm = $sonOrderModel->update(array('gc_confirm_num'=>$con_nums[$id]),array('obj_id'=>$id));
            $res_order_item = $obj_order_items->update(array('gcnum'=>$con_nums[$id]),array('goods_id'=>$goods_id[$id],'order_id'=>$_POST['mainOrder_id']));
        }
        $db->commit();

        if($_POST['opt'] == 'batch'){
//            $status = $this->check_gc(array('mainOrder_id'=>$_POST['mainOrder_id']));
            $status = '1';
        }else{
            $status = '2';
        }
        $obj_collect = $this->app->model('business_goodscollection');
        $obj_collect->update(array('member_id'=>$this->app->member_id,'status'=>$status),array('mainOrder_id'=>$_POST['mainOrder_id']));
        if($status == '2'){
            $order = $this->app->model('orders');
            $order->update(array('c_status'=>'3'),array('order_id'=>$_POST['mainOrder_id']));
        }

        $this->pagedata = array_merge_recursive($this->_editor2(array('mainOrder_id'=>$_POST['mainOrder_id'],'status'=>$status), $page), $this->pagedata);
        $str_html = $this->fetch('site/member/gc_list.html','b2c');
        echo '{success:"'.app::get('b2c')->_('操作成功！').'",_:null,data:"'.addslashes(str_replace("\r\n","",$str_html)).'",reload:null}';
    }

    function check_gc($filter){
        $obj_goods = $this->app->model('business_orders_objects');
        $goods = $obj_goods->getList('*',$filter);
        $status = '0';
        $flg = true;
        foreach($goods as $key => $item){
            if($item['gc_confirm_num'] != '0'){
                $status = '1';
            }
            if($item['gc_confirm_num'] == '0'){
                $flg = false;
            }
        }
        if($flg){
            $status = '2';
        }
        return $status;
    }

    //集货单数据 by yyj 2015/10/13
    function _editor2($filter,$page=1){
        $b_ids = $this->get_business_ids();
        $filter['business_id|in'] = $b_ids;
        $filter['state|noequal'] = '0';
        $result['mainOrder_id'] = $filter['mainOrder_id'];
        if(isset($filter['status'])){
            $result['status'] = $filter['status'];
            unset($filter['status']);
        }
        $filter['has_confirm_num|noequal'] = '0';//供应商确认数据大于0
        if(isset($filter['gc_id'])){
            $result['gc_id'] = $filter['gc_id'];
            unset($filter['gc_id']);
        }
        $b_orders = $this->app->model('business_orders');
        $obj_orders = $this->app->model('business_orders_objects');
        $obj_goods = $this->app->model('goods');
        $goods = $obj_orders->getList('*',$filter);
        $b_order_info = $b_orders->getRow('*',array('childOrder_id'=>$goods[0]['childOrder_id']));
        $result['order_status'] = $b_order_info['order_status'];
        foreach($goods as $key => $item){
            $gdata = $obj_goods->getRow('*',array('goods_id'=>$item['goods_id']));
            if($gdata && isset($gdata['image_default_id'])){
                $goods[$key]['image_default_id'] = $gdata['image_default_id'];
            }
        }

        $imageDefault = app::get('image')->getConf('image.set');
        $result['defaultImage'] = $imageDefault['S']['default_image'];
        $result['goodscollection'] = $goods;
        $result['controller'] = "collect_order";

        return $result;
    }

    /**
     * @Dscription 付款帐单下载 by yyj 2015/10/20
     * @param null
     * @return null
     */
    function pay_download($order_id=0){
        $charset = kernel::single('base_charset');
        //订单信息
        $objOrder = $this->app->model('orders');
        $aData = $objOrder->getRow('*',array('order_id'=>$order_id));

        //会员信息
        $objm = $this->app->model('members');
        $aData['members'] = $objm->getRow('*',array('member_id'=>$aData['member_id']));


        //付款人信息
        $objMc = $this->app->model('member_company');
        $aData['company'] = $objMc->getRow('*',array('company_id'=>$aData['company_id']));

        //订单明细
        $obj_bo = $this->app->model('business_orders');
        $aData['items'] = $obj_bo->get_order_objects($order_id);
        $aData['total_discount'] = $this->cost_total_discount($aData['items']);

        //for nds (Russian Taxes)
        $total_nds = 0;
        foreach($aData['items'] as $k=>$v){
            $cat_id =  $v['cat_id'];
            $parent_cat = $obj_bo->get_item_main_category($cat_id);
            $aData['items'][$k]['parent_cat'] = $parent_cat[0]['parent_id'];
            $nds = 0.18; //tax 18% - it's a law
            $parent_cat = $aData['items'][$k]['parent_cat'];
            $category = $aData['items'][$k]['p_9'];
            $params = unserialize($aData['items'][$k]['params']);
            if($parent_cat == 11 || $cat_id == 11){ //if shoes is for kids, tax 10%
                $nds = 0.1;
                if($category == 113){ //if is category is sport, tax again 18%
                    $nds = 0.18;
                }
                foreach($params['Размерный ряд'] as $k2 => $v2){
                    if($k2 >= 37 && $v2 > 0){ //if size kids shoes  >= 37, then shoes not for kids and tax 18%
                        $nds = 0.18;
                    }
                }
            }
            $aData['items'][$k]['nds'] = $nds;

            //this is for normal price round!!
            $aData['items'][$k]['price'] = floor($aData['items'][$k]['price']);
            $aData['items'][$k]['buy_price'] = floor($aData['items'][$k]['buy_price']);
            $aData['items'][$k]['amount'] = floor($aData['items'][$k]['amount']);
            $aData['items'][$k]['order_amount'] = floor($aData['items'][$k]['order_amount']);
            $aData['items'][$k]['g_discount'] = floor($aData['items'][$k]['g_discount']);
            $aData['items'][$k]['mktprice'] = floor($aData['items'][$k]['mktprice']);

            $aData['items'][$k]['summ'] = $aData['items'][$k]['quantity']*$aData['items'][$k]['price']; //Total Summ
            $aData['items'][$k]['tax'] = $aData['items'][$k]['quantity']*($aData['items'][$k]['price']*$nds);

            if($aData['items'][$k]['mktprice'] != 0){ //if we have a mktprice
                //$aData['items'][$k]['price'] = $aData['items'][$k]['mktprice'];
                $aData['items'][$k]['item_discount'] = $aData['items'][$k]['quantity']*($aData['items'][$k]['mktprice'] - $aData['items'][$k]['price']);
            }
            else{
                $aData['items'][$k]['item_discount'] = 0;
            }

            $total_nds += $aData['items'][$k]['tax']; //total TAX
            $items_discount += $aData['items'][$k]['item_discount']; //total discount
            $normal_summ_with_discount += $aData['items'][$k]['summ'];
            $normal_summ_without_discount += $aData['items'][$k]['summ'] - $aData['items'][$k]['item_discount'];
            $normal_summ += $aData['items'][$k]['summ']; //normal summ
            $normal_count += $aData['items'][$k]['quantity']; //normal count
        }
        //Cyrillic ucfirst
        function mb_ucfirst($text) {
            mb_internal_encoding("UTF-8");
            return mb_strtoupper(mb_substr($text, 0, 1)) . mb_substr($text, 1);
        }

        //帐单信息
        $obj_pay = $this->app->model('payments');
        $pays = $obj_pay->getList('*',array('order_id'=>$order_id),0,-1,'createtime desc');
        $aData['pays'] = $pays[0];
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=payment_order_".date("YmdHms").".xls");

        $this->pagedata['orders'] = $aData;
        $this->pagedata['total_nds'] = floor($total_nds);
        $this->pagedata['items_discount'] = floor($items_discount);
        $this->pagedata['normal_summ'] = $normal_summ;
        $this->pagedata['normal_summ_with_discount'] = $normal_summ_with_discount;
        $this->pagedata['normal_summ_without_discount'] = $normal_summ_without_discount;
        $this->pagedata['normal_count'] = $normal_count;
        $this->pagedata['text_normal_summ'] = mb_ucfirst($this->num2str($normal_summ));
        $this->pagedata['total_count'] = $this->cost_quantity($aData['items']);
        $this->pagedata['up_final_amount'] = mb_ucfirst($this->num2str($aData['final_amount']));

        echo $this->fetch('site/member/pay_order.html');
        exit;
    }

    //商品总量 by yyj 2015/10/21
    function cost_quantity($items){
        $count = 0;
        foreach($items as $key => $item){
            $count = $count + $item['order_num'];
        }
        return $count;
    }

    //商品总折扣 by yyj 2015/10/21
    function cost_total_discount($data){
        $count = 0;
        foreach($data as $key => $item){
            $count = $count + $item['g_discount'];
        }
        return $count;
    }

    /**
     * @Dscription 金额转换大写 by yyj 2015/10/21
     */
    function money($money){
        static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"),
        $cnyunits=array("圆","角","分"),
        $grees=array("拾","佰","仟","万","拾","佰","仟","亿");
        list($ns1,$ns2)=explode(".",$money,2);
        $ns2=array($ns2[1],$ns2[0]);
        $ret=array_merge($ns2,array(implode("",$this->_money_unit(str_split($ns1),$grees)),""));
        $ret=implode("",array_reverse($this->_money_unit($ret,$cnyunits)));
        return str_replace(array_keys($cnums),$cnums,$ret);
    }

    /**
     * @Dscription 格式化数字为中文大写 by yyj 2015/10/21
     */
    function _money_unit($list,$units){
        $ul=count($units);
        $xs=array();
        foreach (array_reverse($list) as $x) {
            $l=count($xs);
            if ($x!="0" || !($l%4)){
                $n= ($x=='0'?'':$x).($units[($l-1)%$ul]);
            } else{
                $n = is_numeric($xs[0][0]) ? $x : '';
            }
            array_unshift($xs,$n);
        }
        return $xs;
    }

    /**
     * @Dscription 俄文金额转换大写 by yyj 2015/10/27
     */
    function num2str($num) {
        $nul='ноль';
        $ten=array(
            array('','один','два','три','четыре','пять','шесть','семь', 'восемь','девять'),
            array('','одна','две','три','четыре','пять','шесть','семь', 'восемь','девять'),
        );
        $a20=array('десять','одиннадцать','двенадцать','тринадцать','четырнадцать' ,'пятнадцать','шестнадцать','семнадцать','восемнадцать','девятнадцать');
        $tens=array(2=>'двадцать','тридцать','сорок','пятьдесят','шестьдесят','семьдесят' ,'восемьдесят','девяносто');
        $hundred=array('','сто','двести','триста','четыреста','пятьсот','шестьсот', 'семьсот','восемьсот','девятьсот');
        $unit=array( // Units
            array('копейка' ,'копейки' ,'копеек',	 1),
            array('рубль'   ,'рубля'   ,'рублей'    ,0),
            array('тысяча'  ,'тысячи'  ,'тысяч'     ,1),
            array('миллион' ,'миллиона','миллионов' ,0),
            array('миллиард','милиарда','миллиардов',0),
        );
        list($rub,$kop) = explode('.',sprintf("%015.2f", floatval($num)));
        $out = array();
        if (intval($rub)>0) {
            foreach(str_split($rub,3) as $uk=>$v) { // by 3 symbols
                if (!intval($v)) continue;
                $uk = sizeof($unit)-$uk-1; // unit key
                $gender = $unit[$uk][3];
                list($i1,$i2,$i3) = array_map('intval',str_split($v,1));
                // mega-logic
                $out[] = $hundred[$i1]; # 1xx-9xx
                if ($i2>1) $out[]= $tens[$i2].' '.$ten[$gender][$i3]; # 20-99
                else $out[]= $i2>0 ? $a20[$i3] : $ten[$gender][$i3]; # 10-19 | 1-9
                // units without rub & kop
                if ($uk>1) $out[]= $this->morph($v,$unit[$uk][0],$unit[$uk][1],$unit[$uk][2]);
            } //foreach
        }
        else $out[] = $nul;
        $out[] = $this->morph(intval($rub), $unit[1][0],$unit[1][1],$unit[1][2]); // rub
        $out[] = $kop.' '.$this->morph($kop,$unit[0][0],$unit[0][1],$unit[0][2]); // kop
        return trim(preg_replace('/ {2,}/', ' ', join(' ',$out)));
    }

    /**
     * 俄文金额计算 by yyj 2015/10/27
     */
    function morph($n, $f1, $f2, $f5) {
        $n = abs(intval($n)) % 100;
        if ($n>10 && $n<20) return $f5;
        $n = $n % 10;
        if ($n>1 && $n<5) return $f2;
        if ($n==1) return $f1;
        return $f5;
    }

    //唛头下载 by yyj 2015/10/30
    function download_shipping_mark($gc_id=0){
        $charset = kernel::single('base_charset');
        //订单信息
        $obj_gc = $this->app->model('business_goodscollection');
        $gcData = $obj_gc->getRow('*',array('gc_id'=>$gc_id));

        //主订单信息
        $objOrder = $this->app->model('orders');
        $shipping_marks = $objOrder->getRow('*',array('order_id'=>$gcData['mainOrder_id']),0,-1,'createtime desc');
        $shipping_marks['goodscollection'] = $gcData;

        //付款人信息
        $objMc = $this->app->model('member_company');
        $shipping_marks['company'] = $objMc->getRow('*',array('company_id'=>$shipping_marks['company_id']));

        //订单明细
        $obj_boo = $this->app->model('business_orders_objects');
        $b_ids = $this->get_business_ids();
        $filter['business_id|in'] = $b_ids;
        $filter['mainOrder_id'] = $gcData['mainOrder_id'];
//        $filter['gc_confirm_num|noequal'] = '0';
        $items = $obj_boo->getList('*',$filter);
        $count = $this->cost_gc_quantity($items);
        $shipping_marks['goodscollection']['items'] = $this->get_sm_items($items);



        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=shipping_mark_".date("YmdHms").".xls");

        $this->pagedata['orders'] = $shipping_marks;
        $this->pagedata['total_count'] = $count;

        echo $this->fetch('site/member/shipping_mark.html');
        exit;
    }

    //唛头明细 by yyj 2015/10/30
    function get_sm_items($items){
        $obj_goods = $this->app->model('goods');
        $obj_brand = $this->app->model('brand');
        $cmData = array();
        $smKey = 0;
        foreach($items as $key => $item){
            $goods = $obj_goods->getRow('brand_id',array('goods_id'=>$item['goods_id']));
            $brand = $obj_brand->getRow('*',array('brand_id'=>$goods['brand_id']));
            $item['brand_name'] = $brand['brand_name'];
            if($item['has_confirm_num'] > 1){
                for($i = 0;$i < $item['has_confirm_num'];$i++){
                    $cmData[$smKey++] = $item;
                }
            }elseif($item['has_confirm_num'] == 1){
                $cmData[$smKey++] = $item;
            }
        }
        return $cmData;
    }
    //计算总销售量 by yyj 2015/10/30
    function cost_gc_quantity($items){
        $count = 0;
        foreach($items as $key => $item){
            $count += $item['has_confirm_num'];
        }
        return $count;
    }
}